In how many ways can we split a string in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

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.

Live Demo

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

Live Demo

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

Live Demo

<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
raja
Published on 17-Jul-2019 14:16:42
Advertisements