How to Convert string to character array in Javascript
- Admin
- Mar 10, 2024
- Typescript Javascript
This example tutorial explains how to convert a string to an array of characters in JavaScript. You can check my other post on Javascript check substring exists in a String
How to get a Character Array from a string javascript?
There are multiple ways we can do it.
- use the split function
The string has a split function
used to split a string into an array of characters or substring with a delimiter Syntax: split(argument)
- The argument is a separator that is used to split into it.
- Returns an array of split elements.
let str = "cloud";
console.log(str.split(""));
Output
[
'c', 'l', 'o', 'u',
'd
]
It works perfectly for a string of alphanumeric characters, However, does not work with Unicode and emoji characters string.
let str = "welcome 😊";
console.log(str.split(""));
Output:
[
'w', 'e', 'l', 'c',
'o', 'm', 'e', ' ',
'�', '�'
]
The split()
function is not safe to use for Unicode strings.
- use the ES6 spread operator
ES6 introduced spread operator, a new syntax to extract data and create a new variable.
let str = "welcome 😊";
let input = [...str];
console.log(input);
In the example, use the spread operator to extract all characters with [...variable]
. Output:
[
'w', 'e', 'l',
'c', 'o', 'm',
'e', ' ', '😊'
]
- use Array from function
- Array provides
from
the function, that takes a string and converts it to a character array.
let str = "welcome 😊";
console.log(Array.from(str));
- use the Object assign function
Object assign function copies a string character into a new array.
This is not safe for Unicode string characters.
let str = "welcome 😊";
var result = Object.assign([], str);
console.log(result);
Output:
[
'w', 'e', 'l', 'c',
'o', 'm', 'e', ' ',
'�', '�'
]
- for of loop
It is another way of retrieving characters from a string and pushing the character to an array.
let str = "welcome 😊";
const result = [];
for (const character of str) {
result.push(character);
}
console.log(result);
You can also use for index syntax to do it.
Iterate each element using for loop, and push an element to the newly created array.
let str = "welcome 😊";
const output = [];
for (let i = 0; i < str.length; i++) {
output.push(str[i]);
}
console.log(output);