String .split() Method

ngl4

Cindy Lam

Posted on January 31, 2022

String .split() Method

In MDN, the definition is - "The .split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array".

We use this method to split a string with a pattern stated in the first parameter, and limits in the second parameter. But they are not required.

From the examples below, please use console.log(splits) to see the output in the console.

const words = 'Hello, I am a Split!'; 

let splits = words.split(); //no parameters
//Output: ['Hello, I am a Split!']

let splits = words.split(' '); //a whitespace
//Output: ['Hello,', 'I', 'am', 'a', 'Split!']

let splits = words.split(','); //a comma
//Output: ['Hello', ' I am a Split!']

let splits = words.split(' ', 3);
//Output: ['Hello,', 'I', 'am']
Enter fullscreen mode Exit fullscreen mode

Split method can also have multiple parameters:

  • We need to use slashes instead of quotations within the split method when there are multiple parameters since we are using regex (Regular Expressions).
const words = 'Hello, I am a Split!'; 

//Using Regex - brackets '/[]/'
let splits = words.split(/[,\s!]/); //comma, whitespace ('\s'), exclamation
//Output: ['Hello', '', 'I', 'am', 'a', 'Split', '']

//Using Regex - pipes '/|/'
let splits = words.split(/,|\s|!/);
//Output: ['Hello', '', 'I', 'am', 'a', 'Split', '']
Enter fullscreen mode Exit fullscreen mode

Additional Notes:

As you noticed there are some empty elements generated from the output, you can use Array filter() method to get rid of them, as below:

const filters = splits.filter(element => element); 
//Output: ['Hello', 'I', 'am', 'a', 'Split']
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ngl4
Cindy Lam

Posted on January 31, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Getting started with NUXT JS
nuxt Getting started with NUXT JS

January 25, 2024

String .split() Method
javascript String .split() Method

January 31, 2022