How to Get Character Array from String in JavaScript ?
Last Updated :
13 Sep, 2024
In JavaScript, you might often find yourself needing to break down a string into individual characters and turn it into an array. This can be useful for iterating over each character, performing string manipulations, or simply working with the data in a different format. Luckily, JavaScript offers several methods to convert a string into a character array. Let’s understand the different methods or approaches to get the character array from the string in the javascript.
Using String split() Method
The str.split() Method 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'
]
JavaScript Array.from() Method
The Array.from() method 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
// Input array
let str = "GeeksforGeeks: A computer science portal";
// Getting char array
let arr = Array.from(str);
// Display output
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', '...
JavaScript Spread Operator
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'
]
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' ]
Please Login to comment...