DEV Community

Cover image for Vanilla JavaScript String Split
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript String Split

Today we are going to look at the JavaScript String.split() method.
This method is called on a string and will return an array of whatever we are splitting on.

Using the JavaScript string.split() method

var string = 'She sells seashells by the seashore';
var array = string.split(' ');
console.log(array);
// (6) ["She", "sells", "seashells", "by", "the", "seashore"]
Enter fullscreen mode Exit fullscreen mode

As you can se we are using the split method with a space as argument. This will return an array of all the words.

If you pass an empty string it will split on each character like so:

var stringTwo = 'Magic words';
var arrayTwo = stringTwo.split('');
console.log(arrayTwo);
// (11) ["M", "a", "g", "i", "c", " ", "w", "o", "r", "d", "s"]
Enter fullscreen mode Exit fullscreen mode

The split comes with a second argument which is the limit of our output array.

var stringThree = 'She sells seashells by the seashore';
var arrayThree = stringThree.split(' ', 3);
console.log(arrayThree);
// (3) ["She", "sells", "seashells"]
Enter fullscreen mode Exit fullscreen mode

View or modify it on this Codepen.

See the Pen Vanilla JavaScript String Split by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)