How To Use Split Function In JavaScript


In this post, we will learn how to split a string in JavaScript. The Split function converts a string object into a substring by comma-separated values. Also,  it converts the string object to an array of strings, and we can access that array bypassing 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.

string.split ([seperator] [, limit]); 

Write the below code for the split function. Here are some examples of splitting the string by space, comma, or special character.

    <title>JavaScript String split() Method</title>  
    <script type="text/javascript">  
        // Split by space  
        var str = "Hello World";  
        var splitted = str.split(" ");  
        document.write('Split by space (space) index 0 : ' + splitted[0] + '<br>');  
        document.write('Split by space (space) index 1 : ' + splitted[1] + '<br><br>');  
        // Split by comma  
        var str1 = "Hello,World";  
        var splitted1 = str1.split(",");  
        document.write('Split by comma (,) index 0 : ' + splitted1[0] + '<br>');  
        document.write('Split by comma (,) index 1 : ' + splitted1[1] + '<br><br>');  
        // Split by special character  
        var str2 = "Hello@World";  
        var splitted2 = str2.split("@");  
        document.write('Split by special character (@) index 0 : ' + splitted2[0] + '<br>');  
        document.write('Split by special character (@) index 1 : ' + splitted2[1] + '<br>');  

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

See the below screenshot for how the result will look,

split string result

Next Recommended Reading JavaScript Split