DEV Community

Cover image for JavaScript Split a String to Array JS methods
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

JavaScript Split a String to Array JS methods

Everyone can code
The best way to split a string to array is to use the split() method in JavaScript.

In this article, I will go over some JavaScript split() methods with some examples.

Syntax of split() method

split(separator, limit)

Here, separator is any ASCII character/letter and limit is a positive number that tells the browser to return specific substrings from an array.

JS split() method code with examples

In this first example, I will take the string "JS is fun". Here, I will use the split() method without any separator or limit and return the value of the whole array. Let's see.

const str = "JS is fun"
str.split()
// ["JS is fun"]
Enter fullscreen mode Exit fullscreen mode

Let's split into individual words and characters

In this second example, I will use the same string as the above example. Here, I will split the string into individual words.

const str = "JS is fun"
str.split(' ')
// ["JS", "is", "fun"]
Enter fullscreen mode Exit fullscreen mode

Now let's split them into individual characters including spaces

const str = "JS is fun"
str.split('')
// ["J", "S", " ", "i", "s", " ", "f", "u", "n"]
Enter fullscreen mode Exit fullscreen mode

Now let's introduce limit parameter

This is a completely optional parameter
In this example, I have used the same string as above examples. Here, in this case I will be add limit parameter to the split() method

const str = "JS is fun"
str.split(' ', 1)
// ["JS"]
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, have a nice day!

Have a nice day.png

Top comments (2)

Collapse
 
muhtoyyib profile image
Akande Olalekan Toheeb

Wow I love this

Collapse
 
dhairyashah profile image
Dhairya Shah

I am glad 🙂