In javascript, we can split a string in 3 ways. One is an old way in which string.split() method is used and later on, ES6 has provided 2 more ways to split a string. In the first way spread operator is used and in the second way array.from() method is used. Let's discuss them in detail.
String.split()
syntax
string.split();
Example
In the following example, string.split() method is used to split the provided string to each individual character.
<html> <body> <script> const str = 'Tutorialspoint' var d = str.split('') document.write(d); </script> </body> </html>
Output
T,u,t,o,r,i,a,l,s,p,o,i,n,t
Spread operator
syntax
[...string];
Example
In the following example, ES6 Spread operator is used to split the provided string into each and individual character. Its usage is very simple when comparing to string.split() method.
<html> <body> <script> const str = 'Tutorix' var d = [...str] document.write(d); </script> </body> </html>
Output
T,u,t,o,r,i,x
Array.from()
syntax
Array.from(str);
Example
In the following example, ES6 Array.from() is used to split the provided string into each and individual character. It works the same as string.repeat() method.
<html> <body> <script> const str = 'Tutorix and Tutorialspoint' var d = Array.from(str); document.write(d); </script> </body> </html>
Output
T,u,t,o,r,i,x, ,a,n,d, ,T,u,t,o,r,i,a,l,s,p,o,i,n,t