JavaScript split() method
Definition and Usage
The split() method is used to split a string into an array of strings.
stringObject.split(separator,howmany)
Parameter Descriptionseparator | Required. A string or regular expression that splits the stringObject from the place specified by this parameter. |
howmany | 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. |
return value
an array of strings. The array is created by splitting the string stringObject into substrings at the boundaries specified by the separator . The strings in the returned array do not include the separator itself.
However, if the separator is a regular expression containing subexpressions, the returned array includes strings that match those subexpressions (but not text that matches the entire regular expression).
Tips and Notes
Note: If the empty string ("") is used as the separator , then each character in the stringObject will be split.
Note: String.split() does the opposite of what Array.join does .
Example
Example 1
In this example, we will split the string differently:
<script type="text/javascript"> var str="How are you doing today?" document.write(str.split(" ") + "<br />") document.write(str.split("") + "<br />") document.write(str.split(" ",3)) </script>
output:
How,are,you,doing,today? H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,? How,are,you
Example 2
In this example, we will split a string with a more complex structure:
"2:3:4:5".split(":") //将返回["2", "3", "4", "5"] "|a|b|c".split("|") //将返回["", "a", "b", "c"]
Example 3
If you wish to split words into letters, or strings into characters, use the following code:
"hello".split("") //可返回 ["h", "e", "l", "l", "o"]
To return only a subset of characters, use the howmany parameter:
"hello".split("", 3) //可返回 ["h", "e", "l"]