Return positions of a regex match() in Javascript?
In modern browsers, you can accomplish this with string.matchAll().
The benefit to this approach vs RegExp.exec()
is that it does not rely on the regex being stateful, as in @Gumbo's answer.
let regexp = /bar/g;
let str = 'foobarfoobar';
let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
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);
}
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);
}