How can I match overlapping strings with regex?

Viewed 13175

Let's say I have the string

"12345"

If I .match(/\d{3}/g), I only get one match, "123". Why don't I get [ "123", "234", "345" ]?

6 Answers

I would consider not using a regex for this. If you want to split into groups of three you can just loop over the string starting at the offset:

let s = "12345"
let m = Array.from(s.slice(2), (_, i) => s.slice(i, i+3))
console.log(m)

Use (?=(\w{3}))

(3 being the number of letters in the sequence)

Related