Tomek Tomek - 1 month ago 7
Javascript Question

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.

Answer

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

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

Or, without capturing the start of the subject string:

var patter = /(abc)(d)e/
var somestring = 'abcde'
var match = somestring.match(patter)
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.