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. JavaScript Split string function accepts two arguments. The first argument is the separator you want to use, and the second integer value is used to restrict the output.
The JavaScript string Split function will not alter the original string. The basic syntax of the string Split function in JavaScript Programming Language is as shown below:
String_Object.split(Separator, limit)
- String_Object: Please specify the valid string on which you want to perform Splitting.
- Separator: Please specify the separator such as empty space, ‘,’ or ‘.’ you want to use. It can be string literal or JavaScript Regular Expression.
- Limit: Please specify the integer number. This argument will restrict the number of elements written by the array.
If you ignore the first argument, the JavaScript Split function split each character and assigns them to an 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
The following set of examples will help you understand the string Split function.
<!DOCTYPE html> <html> <head> <title> Split JavaScript </title> </head> <body> <h1> JavaScript Split Function </h1> <script> 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 \>"); </script> </body> </html>
OUTPUT
ANALYSIS
The following 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, the following statement 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);