JavaScript Split a String to Array JS methods

JavaScript Split a String to Array JS methods

ยท

2 min read

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"]

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"]

Now let's split them into individual characters including spaces

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

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"]

Thank you for reading, have a nice day!

Have a nice day.png

ย