Stephen Melvin
Stephen Melvin

Reputation: 3785

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)\s+([0-9]+)$/i which successfully matches copy and 2 from the above string. How can I find the index of the number 2? I know I can use .index to find the position of the matched test 'copy 2', but I would like to get the position of '2' so that I can increment it.

Upvotes: 1

Views: 746

Answers (4)

Ωmega
Ωmega

Reputation: 43673

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);

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59997

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

Upvotes: 0

PointedEars
PointedEars

Reputation: 14970

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;

Upvotes: 1

katspaugh
katspaugh

Reputation: 17899

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);
});

Upvotes: 1

Related Questions