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:
<!DOCTYPE html>
<html>
<head>
<script>
var alpha = "A, B, C, D, E";
var ar = alpha.split(', '); // split string on comma space
console.log( ar );
</script>
</head>
</html>
Output:
Using use JSON.parse way
This way only work with number, below example gives you an Array of numbers.
<!DOCTYPE html>
<html>
<head>
<script>
var alpha = "1, 2, 3, 4, 5";
var array = JSON.parse("[" + alpha + "]");
console.log( array );
</script>
</head>
</html>
Output:
String by a specific character
var string = 'split-by-dash';
var usingSplit = string.split('-');
// [ 'split', 'by', 'dash' ]
Empty String Separator
If passed empty string as a separator, each character in the string will become an element in the array:
var str = 'abode';
var ar = str.split(''); // empty string separator
console.log( ar ); // [ "a", "b", "c", "d" ]
Regular Expression Separator:
var str = 'favorite desserts: brownies, banana bread, ice cream, chocolate chip cookies';
// regular expression separator
var re = /:\s|,\s/; // split on colon space or comma space
var ar = str.split(re);
console.log( ar );
// [ "favorite desserts", "brownies", "banana bread", "ice cream", "chocolate chip cookies" ]
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.
<!DOCTYPE html>
<html>
<head>
<script>
var str = "STRING";
var arr = [];
var i=0;
for(i; i<=str.length; i++){
arr[i] = str.charAt(i);
}
console.log( arr );
</script>
</head>
</html>
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