Skip to content Skip to sidebar Skip to footer

Javascript Regex: How To Find Index Of Each Subexpression?

Suppose I have the string: BLAH BLAH BLAH copy 2. I want to find the index of the two pieces, the word 'copy' and a number that may follow the word copy. I have the regex: /(copy)\

Solution 1:

If you need to replace the copy number with an incremented number, use replace plus a replacer function:

'BLAH BLAH BLAH copy 2'.replace(/(copy )(\d+)/, function (s, s1, s2) {
    return s1 + (Number(s2) + 1);
});

Solution 2:

If you modify the regular expression slightly, the index of the number can be computed:

var matches= "BLAH BLAH BLAH copy 2".match(/(copy)(\s+)([0-9]+)$/i);
var numberIndex = matches.index +matches[1].length +matches[2].length;

But you really do not need that in order to increment the number:

var matches = "BLAH BLAH BLAH copy 2".match(/(copy)\s+([0-9]+)$/i);
var incremented = (+matches[2]) + 1;

Solution 3:

You should go with regex /^(.*?copy\s+)(\d+)$/i and then length of $1 is a position of $2 (copy number).

Edit: Your test code is (fiddle):

var str = "BLAH BLAH BLAH copy 2";
var m = str.match(/^(.*?copy\s+)(\d+)$/i);
alert("Found '" + m[2] + "' at position " + m[1].length);

Solution 4:

Change the regex /(copy)\s+([0-9]+)$/i to /^((.*)(copy)\s+)([0-9]+)$/i

Then the position of copy is the length of $2 and the position of the numbers is the length of $1. The number will be in $4

Post a Comment for "Javascript Regex: How To Find Index Of Each Subexpression?"