Skip to content Skip to sidebar Skip to footer

What Should The Javascript Match() Regex Function Return?

Take this example: '12345'.match(/(?=(\d{4}))/g); Pasting that line above into my (Chrome) console is returning ['', ''] for me but I am trying to extract an array of ['1234', '23

Solution 1:

You cited the question Match all consecutive numbers of length n. Why not take the code from the accepted answer there (https://stackoverflow.com/a/42443329/4875869)?

What goes wrong with "12345".match(/(?=(\d{4}))/g); is that in ["", ""] the first "" corresponds to the match with $0 (the whole match) = "", $1 (group 1) = "1234", and so for the second "" (the array is like [$0 (match 1), $0 (match 2)] because of g).

If you omit the g ("12345".match(/(?=(\d{4}))/);), you'll get ["", "1234"] ([$0 (the match), $1 (the match)]).


Solution 2:

Edit: It seems regular expressions are not the right tool for the job, as explained by trincot above.

In an attempt to redeem myself, here is a fun solution involving arrays and slice. The literal 4 can be substituted for any other number to achieve a similar effect.

console.log(
  '12345'.split('').map((_, i, a) => a.slice(i, i + 4).join('')).slice(0, 1 - 4)
)

Post a Comment for "What Should The Javascript Match() Regex Function Return?"