Tomek
Tomek

Reputation: 105

How to get the indices of a capturing group in a regular expression in JavaScript?

Given the JavaScript following code

var pattern = /abc(d)e/;
var somestring = 'abcde';
var index = somestring.match(pattern);

I would like to know the start index of a group match, just like Java's Matcher.start() method.

Upvotes: 2

Views: 252

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

You can get the offset of some capture group by capturing everything else before that capture group:

var pattern = /(^.*abc)(d)e/;
var somestring = 'abcde';
var match = somestring.match(pattern);
var index = match[1].length; // this is the offset of `d` in the string

Or, without capturing the start of the subject string:

var pattern = /(abc)(d)e/;
var somestring = 'abcde';
var match = somestring.match(pattern);
var index = match[1].length + match.index; // this is the offset of `d` in the string

match.index is the start index of the match in the string.

Upvotes: 2

Related Questions