Suppose there is a testestest line. If you apply the regular expression /(test)/g , the result will be as follows: test es test . How to make a regular expression capture that intermediate tes test est? How is it properly called?
|
2 answers
Use regexp.exec(str)
If the
gflag is present, the call toregexp.execreturns the first match and remembers its position in theregexp.lastIndexproperty. He will start the subsequent search from this position. If no match is found, then resetsregexp.lastIndexto 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; } |
var res = [] "testestest".replace(/(?=(test))/g, (m, g) => res.push(g)) console.log(res) - Not universally the same. If I got it right. If I have such a regular schedule
/(te)(st)/gand I want to get 3 times piecewiseteandst. How to do it? In my version,teandstwill be inm[1]andm[2]respectively. - Andrey NOP - Although this is how
"testestest".replace(/(?=((te)(st)))/g, (_, p1, p2, p3) => { res.push(p1); res.push(p2); res.push(p3); }), it means it has to be. - Andrey NOP - @ AndreiNOP, it seems to be universal - just shove the entire regular season inside the preview? - Qwertiy ♦
|