How can I get a regex to find every match in javascript?

This works with most pcre engines.
Capture 2, consume 1.

/(?=(\d\d))\d/g

var pat = /(?=(\d\d))\d/g;
var results = [];
var match;

while ((match = pat.exec('1234567')) != null) {
  results.push(match[1]);
}

console.log(results);

Output: 12,23,34,45,56,67


this just won't work in the way you want.

when you specify pattern [0-9]{2}, match() looks up first occurrence of two digit number, then continues search from that place on. as string length is 3, obviously it won't find another match.

you should use different algorithm for finding all two digit numbers. I would suggest using combination of your first match and do one more with following regex

/[0-9]([0-9]{2})/ and combine sets of both first and second run.


You can do it like this:

var str = '121';
var results = [];
var re = /[0-9]{2}/gi, matches;
while (matches = re.exec(str)) {
    results.push(matches[0]);
    re.lastIndex -= (matches[0].length - 1);  // one past where it matched before
}
// results is an array of matches here

It takes multiple calls to .exec() and then you have to manipulate the .lastIndex value so it will start where you want it to look again.

You can see it work here: http://jsfiddle.net/jfriend00/XsNe5/.

You can read about how calling .exec() multiple times works here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec.

function elem(id) {
    return document.getElementById(id);
}

function test() {
  var str = elem("data").value;
  var results = [];
  var re = /[0-9]{2}/gi,
    matches;
  while (matches = re.exec(str)) {
    results.push(matches[0]);
    re.lastIndex -= (matches[0].length - 1);
  }
  elem("result").innerHTML = results.join("<br>");
}

elem("go").onclick = test;
<input id="data" type="text" value="1234567890"><br>
<button id="go">Test</button>
<div id="result"></div>