Return Positions of a Regex Match() in JavaScript

Return positions of a regex match() in Javascript?

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

Find all matching regex patterns and index of the match in the string

exec() only returns a single match. To get all matches with a g​lobal regexp, you have to call it repeatedly, eg.:

var match, indexes= [];
while (match= r.exec(value))
indexes.push([match.index, match.index+match[0].length]);

How to find indexes of all non-matching characters with a JS regex?

Reason

The infinite loop is easy to explain: the regex has a g modifier and thus tries to match multiple occurrences of the pattern starting each matching attempt after the end of the previous successful match, that is, after the lastIndex value:

See exec documentation:

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property

However, since your pattern matches an empty string, and you do not check the condition if the index is equal to lastIndex, the regex cannot advance in a string.

Solution

Use a regex to match any non-alphanumeric chars, /[\W_]/g. Since it does not match empty strings the lastIndex property of the RegExp object will be changed with each match and no infinite loop will occur.

JS demo:

let match, indexes = [];let reg = /[\W_]/g;let str = "1111-253-asdasdas";
while (match = reg.exec(str)) { indexes.push(match.index);}console.log(indexes);

JS regex to match zero-width position either loops forever or doesn't match at all

Use String.prototype.matchAll() to get all the matches.

let teststring = "nesˈo:tkʰo:x";
let re = new RegExp("(?=.*?ˈ)", "g");

[...teststring.matchAll(re)].forEach(result =>
console.log("Match found at " + result.index)
)


Related Topics



Leave a reply



Submit