Sometimes you just need to take strings apart:
var sentence = "Oh a cookie!"
sentence.split(" ");
// [ "Oh", "a", "cookie!" ]
Syntax
The trick is using the correct separator:
myArray.split(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.
Learn More
split()
is just one of several methods that help developers work with strings, to learn more see How To Index, Split, and Manipulate Strings in JavaScript
Originally posted on DigitalOcean Community Tutorials
Author: Ceferino IV Villareal