This article will focus on the use of the split function in Javascript. it can split a string into substrings and return the result as a string array, I believe this article introduces you with a clear understanding of the use of the split function. The split () method is used to split a string into a string array.
Example 1
In this example, we will split the string in different ways:
Var str = "How are you doing today? "Document. write (str. split ("") + "") document. write (str. split ("") + "") document. write (str. split ("", 3) // 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 split strings with more complex structures:
"2: 3: 4: 5 ". split (":") // returns ["2", "3", "4", "5"] "| a | B | c ". split ("|") // returns ["", "a", "B", "c"]
Example 3
Use the following code to split sentences into words:
Var words = sentence. split ('') // or use a regular expression as 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"] // If you only need to return a part of the characters, please use the howmany parameter: "hello ". split ("", 3) // return ["h", "e", "l"]
Instance: