Is there a way to retrieve the (starting) character positions inside a string of the results of a regex match() in Javascript?
The MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range. For example, if the range A1:A3 contains the values 5, 25, and 38, then the formula =MATCH(25,A1:A3,0) returns the number 2, because 25 is the second item in the range.
The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.
We can use the JavaScript regex's exec method to find the index of a regex match. For instance, we can write: const match = /bar/.
\n. Matches a newline character. \r. Matches a carriage return character.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With