DEV Community

Cindy Lam
Cindy Lam

Posted on

2 1

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

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay