Before we get into that, for people who are unfamiliar with split(), here’s a quick refresher.
The function can be called on a string with two parameters. The first is the separator on which we want to split the input string. And the second is the limit which is an optional parameter and specifies the number of times that the separator should be matched.
The separator can be a string or a regex.
Using regex for the separator:
Splitting and keeping the separators
As the MDN docs for Split() state:
But there is a workaround for regular expressions. Using positive lookaheads, we can assert that the regular expression exists, but not actually match it. In simpler words, if parenthesis, that is ( and ), are used in the separator, matched results are included in the array.
Note: \d matches the character class for digits between 0 and 9.
Thus we can use lookarounds to separate strings and keep the separators too! This opens up easier ways to solve some string-parsing problems.