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 toregexp.exec
returns the first match and remembers its position in theregexp.lastIndex
property. He will begin the subsequent search from this position. If no match is found, it resetsregexp.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