split() String Method in JavaScript

Sometimes you just need to take strings apart:

var sentence = "Oh a cookie!"

sentence.split(" ");

// [ "Oh", "a", "cookie!" ]


The trick is using the correct separator:


Common use case

If you leave the separator blank, it will dissect each character.

var pieces = sentence.split("");

// [ "O", "h", " ", "a", " ", "c", "o", "o", "k", "i", "e", "!" ]

Notice that the spaces stay in the resulting array because they were not used as the separator.


🔎 Searching...