Published at
Updated at
Reading time
1min

Today, I found a tiny JavaScript gem that may come in handy. You probably know the string method split().

Call it on a string, define a separator and receive an array of its substrings. Easy peasy!

"Hello party people!".split(' ');
// Array(3) [ "Hello", "party", "people!" ]

The first function parameter (the separator), can be a string value but also a regular expression. By using a regular expression you can devide the original string dependending on different separators.

// Split the string on "-" and "_"
"Hello_party-people!".split(/[-_]/);
// Array(3) [ "Hello", "party", "people!" ]

No matter if your separator is a string value or regular expression, its value is usually not included in the returned array. MDN states this functionality as follows:

When found, separator is removed from the string, and the substrings are returned in an array.

But here's the JavaScript trivia: if you use a regular expression as the separator and this regular expression includes capturing parentheses (( and )), the matching values are included in the result. 😲

// Split the string on "-" and "_"
// but include the separator in the result
"Hello_party-people!".split(/([-_])/);
// Array(5) [ "Hello", "_", "party", "-", "people!" ]

I wasn't aware of this behavior, and I bet it can replace some complex regular expression logic!

If you enjoyed this article...

Join 6.3k readers and learn something new every week with Web Weekly.

Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles