Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.split() by character when string has same character side-by-side

Tags:

javascript

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"] ?

like image 686
Rikard Avatar asked Jul 03 '18 21:07

Rikard


People also ask

How do you split a string after a character?

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.

Does split () alter the original string?

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.


1 Answers

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.

like image 191
Asons Avatar answered Oct 22 '22 22:10

Asons