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 theexec()
method multiple times to find successive matches in the same string. When you do so, the search starts at the substring ofstr
specified by the regular expression'slastIndex
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
How to Create Every Combination Possible for the Contents of Two Arrays
Failed to Load C++ Bson Extension
How to Detect If a Variable Is an Array
Use Dynamic (Variable) String as Regex Pattern in JavaScript
Jquery Post() with Serialize and Extra Data
How to Append a Div Inside an Svg Element
CSS Delivery Optimization: How to Defer CSS Loading
Css3-Animate Elements If Visible in Viewport (Page Scroll)
How to Open New Tab in JavaScript Without Switching to the New Tab
Style.Display='None' Doesn't Work on Option Tags in Chrome, But It Does in Firefox
How to Match Multiple Occurrences with a Regex in JavaScript Similar to PHP's Preg_Match_All()
Detect When an Image Fails to Load in JavaScript
JavaScript Regex Hangs (Using V8)
Window.Open and Pass Parameters by Post Method
Nesting Quotes in JavaScript/Html
Resize a Div on Border Drag and Drop Without Adding Extra Markup