How to Convert string to character array in javascript
- Admin
- Sep 20, 2023
- Typescript Javascript
This example tutorial explains 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 Character Array from a string javascript?
There are multiple ways we can do it.
- use the split function
The string has a split function
with an argument. The argument is a separator that uses to split into it.
Returns an array of split elements.
let str = "cloudhadoop";
console.log(str.split(""));
Output
[
'c', 'l', 'o', 'u',
'd', 'h', 'a', 'd',
'o', 'o', 'p'
]
It works perfectly for a string of alphanumeric characters,
It does not work with Unicode and emoji characters string.
let str = "welcome 😊";
console.log(str.split(""));
Output:
[
'w', 'e', 'l', 'c',
'o', 'm', 'e', ' ',
'�', '�'
]
`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);
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.