To convert a string to an array using JavaScript, the easiest way is with the JavaScript Array.from() method.

var someString = "string";

var stringToArray = Array.from(someString);

console.log(stringToArray);

#Output:
["s", "t", "r", "i", "n", "g"]

If we want to convert a string into an array of elements with a delimiter, we can use the split() method and pass what we want to split the string by as a parameter.

Here is our first example above using the split() method.

var someString = "string";

var stringToArray = someString.split("");

console.log(stringToArray);

#Output:
["s", "t", "r", "i", "n", "g"]

And now an example using a string with spaces.

var someString = "this is a string with spaces";

var stringToArray = someString.split(" ");

console.log(stringToArray);

#Output:
["this", "is", "a", "string", "with", "spaces"]

When working with different objects in JavaScript, the ability to be able to convert objects into other objects easily can be useful.

One such case is if you want to convert a string into an array in JavaScript.

To convert a string into an array using JavaScript, the easiest way is with the Array.from() method.

Array.from() creates a new array with elements containing each character of the string.

Below is a simple example showing you how to convert a string to an array in JavaScript.

var someString = "string";

var stringToArray = Array.from(someString);

console.log(stringToArray);

#Output:
["s", "t", "r", "i", "n", "g"]

Using split() to Split String by Delimiter into Array Using JavaScript

A very useful function in JavaScript is the split() method.

By default, split() converts a string into an array where each item is the words of the string.

You can also use the split() method to split a string by a different delimiter.

With split(), you can convert a string into an array.

For example, if you wanted to split a string by the spaces, then you can use split() in the following way.

var someString = "This is a string with spaces";

var stringToArray = someString.split(" ");

console.log(stringToArray);

#Output:
["This", "is", "a", "string", "with", "spaces"]

Hopefully this article has been useful for you to learn how to convert a string to array in JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024