How do I convert string to array in JavaScript?

To convert a string to an array in JavaScript, you can use the string.split(separator, limit), Array.from(string) methods and the spread ("...") operator. The split() method is used to split the specified string into an array of strings using "separator" as the delimiter. The second parameter determines how many times to divide the matching value. The string.split() method returns a new array without changing the original string. The from() method converts and returns a new array from any object or iterable object; if you pass a string to the method, it will be converted to a character array. You can also use the spread operator ("..."), which is the modern way to convert a string to an array in ES6. In this JavaScript string to array conversion example, we use the split() method. Below you can see more examples of converting a string to array JavaScript with a detailed description of each method. Click Execute to run the JavaScript String to Array Example online and see the result.
How do I convert string to array in JavaScript? Execute
let str = 'JavaScript String to Array Example';

let result = str.split(' ');

console.log(result);
Updated: Viewed: 879 times

Convert string to JavaScript array using split() method

The string.split(separator, limit) method is used in JavaScript to convert a given string into an array of strings using a separator. The second parameter of the split() method specifies how many times to split the matched value; if no limit is specified, the string will be split into all matching values. The string.split() method returns a new array without changing the original string.

JavaScript Convert String to Array with split() Example
let str = 'JavaScript String to Array Example';

console.log(str.split(' ', 1));

// output: ['JavaScript']

Convert string to JavaScript array using from() method

The Array.from() method in JavaScript is used to create an array from any iterable object. The from() method returns a new array instance whose elements correspond to each element in the iterable. In the case of a string, each character of the string is converted to an array element.

JavaScript Convert String to Array with from() Example
let str = 'JavaScript';

console.log(Array.from(str));

// output: ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']

Convert string to JavaScript array using spread operator

In JavaScript ES6 and above, you can use the spread ("...") operator to convert a string to an array.

JavaScript Convert String to Array with Spread Operator Example
let str = 'JavaScript';

console.log([...str]);

// output: ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']

See also