Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return positions of a regex match() in Javascript?

Is there a way to retrieve the (starting) character positions inside a string of the results of a regex match() in Javascript?

like image 979
stagas Avatar asked Feb 19 '10 10:02

stagas


People also ask

What does match () method return?

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.

What does match return in regex?

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.

How do you match index in JavaScript?

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/.

What is \r and \n in regex?

\n. Matches a newline character. \r. Matches a carriage return character.


2 Answers

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);  }
like image 60
Gumbo Avatar answered Sep 29 '22 13:09

Gumbo


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);  }
like image 33
stagas Avatar answered Sep 29 '22 12:09

stagas