I Feel Like I Haven’t Learned the split
Method Properly
Friends, can you use the split
method in JavaScript? I recently realized that I haven't been using it correctly for years, which caused me to get stuck on a problem while solving challenges. Today, I must document this.
Before discussing the problem, let’s review the two basic uses of split
.
Character Parameter
The split
method is used for string splitting, and the most common form is using a specific character to split the original string. For example:
'as:st:vii'.split(':')
// ['as', 'st', 'vii']
Using :
to split the original string results in an array. This is the usage most people are familiar with.
Regex Parameter
Sometimes splitting isn’t done by a specific character but by a class of characters, like numbers:
'as2st3vii'.split(/\d/)
// ['as', 'st', 'vii']
The regex \d
represents all digits, treating any digit as a separator, which is very flexible.
Problem One
So why do I say I haven’t learned it properly? Look at the following code:
`asabstcdvii`.split(/(ab|cd)/)