DEV Community

loading...
Cover image for How to convert each character in the string to an array using the Object.assign() method in JavaScript?

How to convert each character in the string to an array using the Object.assign() method in JavaScript?

MELVIN GEORGE
Hi, I'm Melvin George, A web developer, and a blogger.
Originally published at melvingeorge.me ・1 min read

Originally posted here!

To convert each character in a string into an array, we can use the assign() method from the global Object object in JavaScript.

Consider a string called Hello! like this,

// random string
const str = "Hello!";
Enter fullscreen mode Exit fullscreen mode

Now to convert each character in this string into an array, let's use the Object.assign() method and

  • pass an empty array [] as the first argument to the method
  • and the string as the second argument to the method
  • the method returns a new array.

It can be done like this,

// random string
const str = "Hello!";

// convert each characters in string to array
const strArr = Object.assign([], str);

console.log(strArr); // ["H", "e", "l", "l", "o", "!"]
Enter fullscreen mode Exit fullscreen mode

Now if you look at the output of the strArr, we can see that the string is successfully converted to an array.

See the above code live in JSBin.

That's all πŸ˜ƒ!

Feel free to share if you found this useful πŸ˜ƒ.


Discussion (0)