JavaScript How to Get Character Array from String? (original) (raw)
Last Updated : 09 Jan, 2025
Here are the various methods to get character array from a string in JavaScript.
**1. Using String split() Method
The **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.
JavaScript `
let s = "GeeksforGeeks"; let a = s.split(""); console.log(a);
`
Output
[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's' ]
**2. Using JavaScript Spread Operator
The Spread operator allows an iterable to expand in place. In the case of a string, it breaks string to character and we capture all the characters of a string in an array.
JavaScript `
let s = "GeeksforGeeks"; console.log([...s]);
`
Output
[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's' ]
**3. Using 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.
JavaScript `
let s = "GeeksforGeeks"; let a = Array.from(s);
console.log(a);
`
Output
[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's' ]
**4. Using for ... of Loop
The for...of loop provides manual control over iteration to create a character array.
JavaScript `
const s = 'GeeksforGeeks'; const a = []; for (const s1 of s) { a.push(s1); } console.log(a);
`
Output
[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's' ]
**Which Approach Should You Use?
**Approach | **When to Use |
---|---|
**Using String.split() | Best for simplicity and readability. |
**Using Spread Operator | Ideal for concise ES6+ code. |
**Using Array.from() | Suitable when you need additional transformations during array creation. |
**Using for..of Loop | Useful when custom processing is required for each character. |
The **String.split() and **Spread Operator methods are the most commonly used for their simplicity and readability. Use **Array.from() or **for...of when additional customization or transformations are required.