Artboard 16light, inspiration, solution, idea, innovation,Google Sheets iconSwift icon
Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

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

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

const string = "Hello party people!";
console.log(string.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.

const string = "Hello_party-people!";
console.log(string.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 resulting 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 paratheses (( and )), the matching values are included in the result. ๐Ÿ˜ฒ

const string = "Hello_party-people!";
console.log(string.split(/([-_])/));
// Array(5) [ "Hello", "_", "party", "-", "people!" ]

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

Related Topics

Related Articles