In JavaScript, you can use the split() method of a string to convert a string into a string array. This method can split the string into a string array according to the specified delimiter; the syntax format is "string .split(separator)", the separator can be empty or null character.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, you can use the split() method of string to convert a string into a string array.
The split() method is used to split a string into a string array.
Syntax
string.split(separator,limit)
Parameters | Description |
---|---|
separator | Optional. A string or regular expression to split the string Object from where specified by this parameter. |
limit | Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings will be returned than the array specified by this parameter. If this parameter is not set, the entire string will be split regardless of its length. |
If an empty string ("") is used as a separator, each character in the string will be split.
Return value: a string array.
Example: Convert string to string array
var str="Hello World !"; console.log(str.split(" ")); console.log(str.split(""));
Output:
Example:If the parameter is a regular expression, the split() method can split the matching text as the delimiter.
var str="Hello World !"; console.log(str.split(" ")); console.log(str.split(""));var s = "a2b3c4d5e678f12g"; var a = s.split(/\d+/); //把以匹配的数字为分隔符来切分字符串 console.log(a); //返回数组[a,b,c,d,e,f,g] console.log(a.length); //返回数组长度为7
Example:
If the text matched by the regular expression is located at the edge of the string, the split() method also performs the splitting operation and adds a Empty array.
var s = "122a2b3c4d5e678f12g"; var a = s.aplit(/\d+/); console.log(a); console.log(a.length);
If the specified delimiter is not found in the string, an array containing the entire string is returned.
Example:
The split() method supports a second parameter, which is an optional integer used to specify the maximum length of the returned array. . If this parameter is set, the length of the returned array will not be greater than the value specified by this parameter; if this parameter is not set, the entire string will be split without considering the array length.
var s = "JavaScript"; var a = s.split("", 4); //按顺序从左到右,仅分切4个元素的数组 console.log(a); //返回数组[J,a,v,a] console.log(a.length); //返回值为4
【Related recommendations: javascript learning tutorial】
The above is the detailed content of How to convert string to string array in javascript. For more information, please follow other related articles on the PHP Chinese website!