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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay