The function of javascript split is to split a string into a string array. Its usage syntax is "stringObject.split(separator,howmany)".
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
What is the usage of javascript split?
The split() method is used to split a string into an array of strings.
Syntax
stringObject.split(separator,howmany)
Parameters
separator required. A string or regular expression to split the stringObject from where 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
A string array. The array is created by splitting the string stringObject into substrings at the boundaries specified by separator. The strings in the returned array do not include the separator itself.
However, if separator is a regular expression that contains 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 a separator, each character in the stringObject will be split between them.
Note: The operation performed by String.split() is the opposite of the operation performed by Array.join.
Example
Example 1
In this example, we will split the string in different ways:
<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
Using the following code, the sentence can be Split into words:
var words = sentence.split(' ')
Or use regular expression as separator:
var words = sentence.split(/\s+/)
Example 4
If you want to split words into letters, or split strings into characters , you can use the following code:
"hello".split("")//可返回 ["h", "e", "l", "l", "o"]
If you only need to return a part of the characters, please use howmany parameters:
"hello".split("", 3)//可返回 ["h", "e", "l"]
Recommended learning: "javascript basic tutorial"
The above is the detailed content of What is the usage of javascript split. For more information, please follow other related articles on the PHP Chinese website!