Subscribe

Vanilla JavaScript String Split

✍️

Today we are splitting a string into an array

3 Jun, 2020 · 2 min read

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

const string = 'She sells seashells by the seashore';
const array = string.split(' ');
console.log(array);
// (6) ["She", "sells", "seashells", "by", "the", "seashore"]

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:

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

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

const stringThree = 'She sells seashells by the seashore';
const arrayThree = stringThree.split(' ', 3);
console.log(arrayThree);
// (3) ["She", "sells", "seashells"]

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 1900 devs and subscribe to my newsletter