Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all indexes of a pattern in a string?

Tags:

javascript

I want something like this:

"abcdab".search(/a/g) //return [0,4]

Is it possible?

like image 948
Gadi A Avatar asked Mar 31 '12 16:03

Gadi A


2 Answers

You can use the RegExp#exec method several times:

var regex = /a/g;
var str = "abcdab";

var result = [];
var match;
while (match = regex.exec(str))
   result.push(match.index);

alert(result);  // => [0, 4]

Helper function:

function getMatchIndices(regex, str) {
   var result = [];
   var match;
   regex = new RegExp(regex);
   while (match = regex.exec(str))
      result.push(match.index);
   return result;
}

alert(getMatchIndices(/a/g, "abcdab"));
like image 168
Niklas B. Avatar answered Oct 17 '22 04:10

Niklas B.


You could use / abuse the replace function:

var result = [];
"abcdab".replace(/(a)/g, function (a, b, index) {
    result.push(index);
}); 
result; // [0, 4]

The arguments to the function are as follows:

function replacer(match, p1, p2, p3, offset, string) {
  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
  return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString);  // abc - 12345 - #$*%
like image 6
Joe Avatar answered Oct 17 '22 03:10

Joe