Let’s get started.
Method 1 –
In this first method, we will use the most common
split() method to convert the string into an array. It will split the string and make a new array from them.
Let’s see some examples of a
split() method to convert the string into an array of substrings and return a new array.
[ 'Welcome', 'to', 'Your Blog Coach' ]
So as you see we can use the
split() method to convert the string into an array of its substrings. You can split the string with any characters.
Method 2 –
In this method, we will use the
Object.assign() method to convert the string into an array. It will copy all the values and properties from one or more source objects to the target object.
You have to pass the square brackets
[ ] as the first parameter of assign() and the string will be the second parameter. Let’s see an example.
[ 'A', 'w', 'e', 's', 'o', 'm', 'e' ]
Object.assign() methods will not work with the UTF-8 code characters like emojis characters. It will convert the UTF-8 characters in this type of character � which is not correct.
Method 3 –
So you have to use this three dots operator as a prefix of the string and wrap the string into square brackets (
[ ]) to make it an array. Let’s see examples.
[ 'Y', 'o', 'u', 'r', 'B', 'l', 'o', 'g', 'C', 'o', 'a', 'c', 'h' ]
You can see in the above example, that it can convert the whole word or string into an array. You cannot split the string from a specific place, it split through the character of the string.
If the string has spaces or any operator then it will also make an array of elements. Let’s see an example of it.
[ 'Y', 'o', 'u', 'r', '-', 'B', 'l', 'o', 'g', ' ', 'C', 'o', 'a', 'c', 'h' ]
You can see we have a string with space and operator (-) and it is also converted into array elements. The interesting thing is that you can convert the emojis characters (😂, 😊) into array elements using this method. We will see the example below.
Method 4 –
You just have to pass the string variable into Array.from() method and it will convert the string into elements of an array. Let’s have an example.
[ 'J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't' ]
It can split the emojis character correctly and convert them into array elements. You can use the UTF-8 code characters also in this method. Let’s see an example.
[ '😂', 'J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't', '😊' ]
You can see the emojis character also converted into array elements. You can use any emojis or UTF-8 code characters.
Hope this tutorial is helpful for you and that you like it. If you have any questions please do ask me in the comment section, I will respond to you as soon as possible.