How To Use Split Function In JavaScript

In this post, we will learn how to split a string in JavaScript. The Split function is used to convert a string object into substring by comma separated values. Also,  it converts the string object to an array of strings and we can access that array by passing its value. In this post, we will split a string by different examples, like split by space or any special character.

Let's start coding.

Below is the syntax of the split method.

  1. string.split ([seperator] [, limit]); 
Write the below code for the split function. Here are some examples to split the string by space, comma, special character.
  1. <html>  
  2. <head>  
  3.     <title>JavaScript String split() Method</title>  
  4. </head>  
  5. <body>  
  6.     <script type="text/javascript">  
  7.         // Split by space  
  8.         var str = "Hello World";  
  9.   
  10.         var splitted = str.split(" ");  
  11.   
  12.         document.write('Split by space (space) index 0 : ' + splitted[0] + '<br>');  
  13.         document.write('Split by space (space) index 1 : ' + splitted[1] + '<br><br>');  
  14.   
  15.         // Split by comma  
  16.         var str1 = "Hello,World";  
  17.   
  18.         var splitted1 = str1.split(",");  
  19.   
  20.         document.write('Split by comma (,) index 0 : ' + splitted1[0] + '<br>');  
  21.         document.write('Split by comma (,) index 1 : ' + splitted1[1] + '<br><br>');  
  22.   
  23.         // Split by special character  
  24.         var str2 = "Hello@World";  
  25.   
  26.         var splitted2 = str2.split("@");  
  27.   
  28.         document.write('Split by special character (@) index 0 : ' + splitted2[0] + '<br>');  
  29.         document.write('Split by special character (@) index 1 : ' + splitted2[1] + '<br>');  
  30.     </script>  
  31. </body>  
  32. </html> 

In the above example, we tried to split a string object by space, comma (,), special character (@) and accessed the split string using its index like "Hello, World". Here, we did split this string by comma and after splitting, we accessed this by its index like 0 or 1 and so on. Split string index depends on the length of the split string.

See the below screenshot for how the result will look,

split string result