How to Get Character Array from String in JavaScript ?
The string is defined as a sequence of characters. In this article, we will learn how to get a character array from a string in JavaScript.
The str.split() function is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.
Syntax:
str.split(separator, limit);
Example: In this example, we will get a character array from the string using the JavaScript split() method.
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() function creates a new array instance from a given array. In case of string, every alphabet of the string is converted to an element of the new array instance, and in the case of integer values, a new array instance simply takes the elements of the given array.
Syntax:
Array.from(str);
Example: In this example, we will get a character array from the string using the Array.from() function in JavaScript.
Javascript
let str = "GeeksforGeeks: A computer science portal" ;
let arr = Array.from(str);
console.log(arr);
|
Output
[
'G', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'G', 'e', 'e', 'k', 's', ':',
' ', 'A', ' ', 'c', 'o', 'm', 'p',
'u', 't', 'e', 'r', ' ', 's', 'c',
'i', 'e', 'n', 'c', 'e', ' ', 'p',
'o', 'r', '...
The Spread operator allows an iterable to expand in place. In the case of a string, it example string into character and we capture all the characters of a string in an array.
Syntax:
let variableName = [ ...value ];
Example: In this example, we will get a character array from the string using the spread operator in JavaScript.
Javascript
let str = "GeeksforGeeks" ;
console.log([...str]);
|
Output
[
'G', 'e', 'e', 'k',
's', 'f', 'o', 'r',
'G', 'e', 'e', 'k',
's'
]
Method 4: Using for … of Loop
JavaScript for of statement iterates over the values of an iterable object (like Array, Map, Set, arguments object, …,etc), executing statements for each value of the object.
Syntax:
for ( variable of iterableObjectName) {
...
}
Example: In this example, we are using for…of… loop.
Javascript
const s = '12345' ;
const a = [];
for (const s1 of s) {
a.push(s1);
}
console.log(a);
|
Output
[ '1', '2', '3', '4', '5' ]
You can learn JavaScript from this JavaScript Tutorial and practice on JavaScript Examples.
Last Updated :
28 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...