Javascript

Convert String into Array using Javascript split() method

If you want to convert strings into array in javascript, then the split() method in javascript is the perfect method for this. In this article, we’ll be talking about how to convert various types of strings into an array in javascript.

Also Read: Convert Array to String in Javascript using Array.join()

What is the Javascript split() method?

The split() method is JavaScript’s inbuilt method which returns an array of substrings obtained by splitting a string on a separator you specify. The separator can be a string, operator or regular expression.

Here is an example of Javascript split() method in working

var shoppingList = 'apples,pears,cookies,bread';

// Returns ["apples", "pears", "cookies", "bread"]
var shoppingListArray = shoppingList.split(',');

Here we can see that the split method, split the entire string based on the given separator and gives us an array of splitted strings.

Syntax of Javascript split() method

str.split(separator, limit)

Separator – It is the value by which we want to split our string. If the separator is unspecified then the entire string becomes one single array element.

The same also happens when the separator is not present in the string. If the separator is an empty string (“”) then every character of the string is separated.

Limit – Limit refers to the upper limit on the number of splits to found in the given string.

Convert Comma separated strings into an array in Javascript

The example given below shows how to convert a comma-separated string into an array in JavaScript.

const names = 'Harry,John,Clark,Peter,Rohn,Alice';
const nameArr = names.split(',');
console.log(nameArr);
// output
['Harry', 'John', 'Clark', 'Peter', 'Rohn', 'Alice']

So, this is all about the Javascript split() method and that’s how you can convert a comma-separated string into an array in javascript.

Leave a Comment