{

How to Convert string to character array in 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 split function

The string has a split function with argument. The argument is a separator that uses to split into it.

Returns 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.

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.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.