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

  • A+
Category:Languages

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

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: