In the project, you need to analyze and divide a regular string into a string array. Split definition and usage
The split () method is used to split a string into a string array.
Syntax
StringObject. split (separator, howator) parameter description
Separator is required. String or regular expression, which separates stringObject from the specified place.
Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings are returned than the array specified by this parameter. If this parameter is not set, the entire string is split, regardless of its length.
Return Value
A string array. This array is created by dividing the string stringObject into substrings at the boundary specified by separator. The strings in the returned array do not include the separator itself.
However, if separator is a regular expression that contains a subexpression, the returned array contains the strings that match the subexpression (but does not include the text that matches the entire regular expression ).
Tips and comments
NOTE: If an empty string ("") is used as a separator, each character in the stringObject is separated.
Note: The operations executed by String. split () are the opposite to those executed by Array. join.
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
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Output:
The Code is as follows:
How, are, you, doing, today?
H, o, w, a, r, e, y, o, u, d, o, I, n, g, t, o, d,, y ,?
How, are, you example
In this example, we split strings with more complex structures:
"2: 3: 4: 5". split (":") // Returns ["2", "3", "4", "5"]
"| A | B | c". split ("|") // ["", "a", "B", "c", ""]
Example 3
Use the following code to split sentences into words:
Var words = sentence. split ('') or use a regular expression as the separator:
Var words = sentence. split (/\ s +/) Example 4
If you want to split words into letters or strings into characters, use the following code:
"Hello ". split ("") // Returns ["h", "e", "l", "l", "o, use the howmany parameter:
"Hello". split ("", 3) // you can return ["h", "e", "l"]
The usage of js split is nothing else. Let's take a look at the examples below.
<Script language = "javascript"> str = ","; // This is a string var strs = new Array (); // defines an Array strs = str. split (","); // character segmentation for (I = 0; I <strs. length; I ++) {document. write (strs [I] + "<br>"); // split character output} script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
The output result is
The Code is as follows:
2
2
3
5
6
6
Js split divides a string into multiple strings by specific characters. you should understand it at a glance.