THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This example tutorial explains to convert a string to an array of characters in javascript.
There are multiple ways we can do it.
The string has a split function
with argument. The argument is a separator that uses to split into it.
Returns array of splitted 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.
let str="welcome 😊";
let input=[... str]
console.log(input);
Output:
[
'w', 'e', 'l',
'c', 'o', 'm',
'e', ' ', '😊'
]
from
the function, that takes a string and converts it to a character array.let str="welcome 😊";
console.log(Array.from(str))
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', ' ',
'�', '�'
]
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.
🧮 Tags
Recent posts
Multiple ways to Create an Observable with Delay| Angular examples How to check null or empty or undefined in Angular? Difference between iter, iter_mut, and into_iter in Rust example Angular Observable Array Examples Angular ngIf examplesRelated posts