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 2

    Use regexp.exec(str)

    If the g flag is present, the call to regexp.exec returns the first match and remembers its position in the regexp.lastIndex property. He will start the subsequent search from this position. If no match is found, then 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

       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)/g and I want to get 3 times piecewise te and st . How to do it? In my version, te and st will be in m[1] and m[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