Return positions of a regex match() in Javascript?
exec
returns an object with a index
property:
var match = /bar/.exec("foobar");if (match) { console.log("match found at " + match.index);}
And for multiple matches:
var re = /bar/g, str = "foobarfoobar";while ((match = re.exec(str)) != null) { console.log("match found at " + match.index);}
Here's what I came up with:
// Finds starting and ending positions of quoted text// in double or single quotes with escape char support like \" \'var str = "this is a \"quoted\" string as you can 'read'";var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;while (match = patt.exec(str)) { console.log(match.index + ' ' + patt.lastIndex);}
From developer.mozilla.org docs on the String .match()
method:
The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.
When dealing with a non-global regex (i.e., no g
flag on your regex), the value returned by .match()
has an index
property...all you have to do is access it.
var index = str.match(/regex/).index;
Here is an example showing it working as well:
var str = 'my string here';var index = str.match(/here/).index;alert(index); // <- 10
I have successfully tested this all the way back to IE5.