String to Array in JavaScript
Last Updated :
17 Jul, 2023
In this article, you will learn how to convert a string to an array data type in JavaScript.
There are various methods to convert a String to an Array that is described below:
The Spread Operator represented by (…) allows any iterable to expand like an array into individual elements i.e. string to characters.
Syntax:
let Arr = [...str];
Example: In this example, Spread Operator is used to convert a String to an array.
Javascript
let str= "GeeksforGeeks" ;
let arr = [];
arr = [...str];
console.log(arr);
|
Output
[
'G', 'e', 'e', 'k',
's', 'f', 'o', 'r',
'G', 'e', 'e', 'k',
's'
]
Approach 2: Naive Method
This approach includes traversing every character of the string and pushing that to the array.
Example: In this example, we will use a loop to iterate the given string and push the string character into an array.
Javascript
let str= "GeeksforGeeks" ;
let len = str.length;
let arr = [];
for (let i = 0; i < len; i++) {
arr.push(str[i]);
}
console.log(arr);
|
Output
[
'G', 'e', 'e', 'k',
's', 'f', 'o', 'r',
'G', 'e', 'e', 'k',
's'
]
The String Split() Method takes the pattern as an argument and returns the target string as a list or array. The separator represents the function where to split and the limit represents the number of substrings or lengths up to which the string will be processed.
Syntax:
split(separator); // or
split(separator, limit);
Example:
Javascript
let str= "GeeksforGeeks" ;
let arr = str.split( '' );
console.log(arr);
|
Output
[
'G', 'e', 'e', 'k',
's', 'f', 'o', 'r',
'G', 'e', 'e', 'k',
's'
]
The Array from() method returns a new instance of an array from the object provided in the arguments.
Syntax:
Array.from(object, mapFunction, thisValue);
Example: In this example, we will pass a string into Array from() method to convert it into an array.
Javascript
let str= "GeeksforGeeks" ;
let arr = Array.from(str)
console.log(arr);
|
Output
[
'G', 'e', 'e', 'k',
's', 'f', 'o', 'r',
'G', 'e', 'e', 'k',
's'
]
Method 5: Using slice() Method
The call() method is used to invoke the slice() method, treating the string as this value. This creates a new array where each character in the string is an element.
Example:
Javascript
let str = "Welcome to GeeksforGeeks" ;
let array = Array.prototype.slice.call(str);
console.log(array);
|
Output
[
'W', 'e', 'l', 'c', 'o',
'm', 'e', ' ', 't', 'o',
' ', 'G', 'e', 'e', 'k',
's', 'f', 'o', 'r', 'G',
'e', 'e', 'k', 's'
]
Share your thoughts in the comments
Please Login to comment...