Check the following examples and their outcome:
'222'.split('') // ["2", "2", "2"]
'222'.split('2') // ["", "", "", ""]
'2a22a'.split('2') // ["", "a", "", "a"]
Why is the last example not ["", "a", "", "", "a"]
?
To split a string at a specific character, you can use the split() method on the string and then pass that character as an argument to the split() method in JavaScript.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Because it splits like this
'2a22a'.split('2') becomes "" (2) "a" (2) "" (2) "a"
where the "a" on each side of the 22 will be one array item each, but between the 22, there will be only one "".
So if one add "a" both at the beginning and between the 22, it will be more clear.
'a2a2a2a'.split('2') becomes ["a", "a", "a", "a"]
You could also say; every split character, here 2
, will become a comma ,
in the array definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With