Javascript split usage and examples, with splitting string into array, regex and paying attention

Lionsure 2020-06-21 Original by the website

The split() method is used to split a string by a specified character or string, and the split string is returned as a character array in javascript.


I. Syntax of javascript split

string.split(separator, [limit])


II. Arguments description:

1. Separator: required, it is a separator, which can be a character or a regular expression;

2. Limit: optional, it is used to specify the maximum length of the returned array; in practical applications, when the string to be split has multiple substrings, and only want to take the first few, just use the limit argument.


III. Pay attention to the problem

1. The returned array element(substring) does not contain the separator;

2. If there is no specified separator in the string or null is used as the separator, all characters in the string are returned as an element of the array;

3. If separator is empty(""), then each character in string is returned as an element of the array;

4. If separator is composed of regular expressions, the place where the string matching the regular expression in the string is used as a separating point, and the separated string is returned as an array element.



IV. Examples of javascript split


Example 1: Javascript split string

var str = "abk|gei|uie";

var arr = str.split('|');//Return the array: ["abk", "gei", "uie"], Javascript split string into array

var arr1 = str.split('|', 2);//Return the array: ["abk", "gei"], Javascript split string into array


Example 2: Pay attention to the problem

var str = "1,2,3";

var arr = str.split();//Return the array: ["1,2,3"]

var arr1 = str.split(null);//Return the array: ["1,2,3"]

var arr2 = str.split("");//Return the array: ["1, ",", "2", ",", "3"]

var arr3 = str.split(",");//Return the array: ["1,  "2", "3"]


Example 3: Separator is a regular expression(Javascript split regex)

var str = "Hello World";

var arr = str.split(/\s+/);//Return the array: ["Hello", "World"]

Or var arr = str.split(" ");//Return the array: ["Hello", "World"]


Example 4: Practical application

If you want to get the parameters of the current URL, the code is as follows:

function GetUrlFullParam() {
              var url = document.location.toString();
              var arr = url.split("?");

              if(arr.length > 1)
                     return arr[1];

If you want to get the value of the specified parameter of the current URL, please see the article "Javascript get current url, domain from url, relative path, parameter and parameter value", which can be found by clicling it on this website.