Search code examples
javascriptjqueryregexsubstr

How to apply a regex just for a part of string?


I have a string like this:

var str = "this is test
            1. this is test
            2. this is test
            3. this is test
            this is test
             1. this test   
             2. this is test
            this is test";

Also I have this regex:

/^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m

This capturing group $1 returns 2 from above string.

Now I have a position number: 65 and I want to apply that regex in this range of the string: [0 - 65]. (So I have to get 3 instead of 2). In general I want to limit that string from first to a specific position and then apply that regex on that range. How can I do that?


Solution

  • The simplest way is to apply it to just that substring:

    var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
    // Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^
    

    Example:

    var str = "this is test\n1. this is test\n2. this is test\n3. this is test\nthis is test\n1. this test   \n2. this is test\nthis is test";
    var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
        // Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^
    
    document.body.innerHTML = match ? "First capture: [" + match[1] + "]" : "(no match)";