javascript – How to catch overlapping matches in regular expressions?

Question:

Let's say there is a line testestest . If we apply the regular expression /(test)/g , the result will be: test es test . How do I make the regex catch that intermediate tes test est too? What is it called correctly?

Answer:

Use regexp.exec(str)

If the g flag is present, then the call to regexp.exec returns the first match and remembers its position in the regexp.lastIndex property. He will begin the subsequent search from this position. If no match is found, it resets regexp.lastIndex to zero.

let s = "testestest";
let r = /test/g;
let m;
while (m = r.exec(s)) {
  console.log("Match: " + m[0] + ", pos: " + m.index);
  r.lastIndex = m.index+1;
}

learn.javascript.ru: RegExp and String Methods

Scroll to Top