JavaScript Split String

The JavaScript Split function is a String function, which is used to split the original string into an array of substring based on the separator we specified and returns them in an array. The JavaScript string Split function will not alter the original string. 

JavaScript Split string function accepts two arguments. And the syntax of the string Split function in JavaScript is

String_Object.split(Separator, limit)
  • Separator: It can be string literal or JavaScript Regular Expression. For example, empty space, ‘,’ or ‘.’
  • Limit (integer): Restrict the number of elements written by the string array.

If you ignore the first argument, the JavaScript Split function split each character and assigns them to a string array. If you omit the second index, the JS string Split function starts from the beginning and continues till the end.

JavaScript Split Function Example

This example will help you understand the js split string function.

<!DOCTYPE html>
    <title> Split JavaScript </title>
    <h1> JavaScript Split Function </h1>
    var Str1 = "We are Abc working in abc company since abc years";
    var Str2 = Str1.split("");
    var Str3 = Str1.split(" ");
    var Str4 = Str1.split(" ", 4);
    var Str5 = Str1.split(/abc/i);
    var Str6 = Str1.split(/abc/i, 2);
    document.write(Str2 + "<br \>");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
    document.write(Str6 + "<br \>");
JavaScript SPLIT Function

This JS string split statement will split the original string into individual characters

var Str2 = Str1.split("");

Next, we used the empty space as a separator for the JavaScript Split string function. So, it will split the original string into an array of words based on white space

var Str3 = Str1.split(" ");

We used the second argument to restrict the JavaScript array output to four.

var Str4 = Str1.split(" ", 4);

Next, we used substring “abc” as a separator for the Js Split String Function. Here i is the regular expression to perform case insensitive search

var Str5 = Str1.split(/abc/i);