0

I am trying to split any string into a list of 3-character substrings.

For example: abcdefgh splits into:

abc , bcd , cde , def , efg , fgh

So I wrote the following regex :

"abcd".match(/.{1,3}/g);

but it outputs as abc , d. How could I achieve the output as described above?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Dan Hick
  • 29
  • 3
  • This is not a duplicate. The linked duplicate wants a string split every 3 characters. 'abcdefgh' => 'abc , bcd , cde , def , efg , fgh' is not splitting every 3 characters – Tom_B Sep 13 '18 at 17:02

1 Answers1

0

Since there can not be overlapping matches, you need to use something that prohibits regex engine from advancing and consuming the string.

The answer is lookarounds, specifically: positive lookahead. It won't consume string and can have captuirng group inside, which you can then access.

Use this pattern: (?=([a-z]{3})). It asserts, that what follows current position are three lowercase letters. Since it's wrapped in lookahead, it won't advance behind found three letters.

In result, you will get 6 matches, which will be empty, but each match will contain capturing group, which will contain three letters.

Demo

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69