Convert String to Array JavaScript |split, Separator, Regex, JSON.parse

How can I convert a string to a JavaScript array?

You can use JSON.parse or .split() method to convert String to Array JavaScript. JavaScript’s string split method returns an array of substrings obtained by splitting a string on a separator you specify.

The separator can be a string or regular expression or special char like a comma.

Examples of String to Array JS

Let’s see some basic and simple examples.

Using the split method

Example of convert comma separated string to array javascript.

Note: If you don’t pass any separator argument to the split method, the resulting array will have a single element consisting of the entire string:

Output:

convert comma separated string to array javascript

Using use JSON.parse way

This way only work with number, below example gives you an Array of numbers.

Output:

Convert String to Array JavaScript

String by a specific character

Empty String Separator

If passed empty string as a separator, each character in the string will become an element in the array:

Regular Expression Separator:

Q: How to convert string to array javascript without split method?

Answer: If you want do it manually, without any JavaScript methods. Try the below code using a for loop.

convert string to array javascript without split method

Do comment if you have any questions and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.