Home >Web Front-end >JS Tutorial >Summary of how to use split() in JavaScript_javascript tips
The split() method is used to split a string into an array of strings.
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)) //输出: //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
Use the following code to split sentences into words:
var words = sentence.split(' ') //或者使用正则表达式作为 separator: var words = sentence.split(/\s+/)
Example 4
If you want to split a word into letters, or a string into characters, use the following code:
"hello".split("") //可返回 ["h", "e", "l", "l", "o"] //若只需要返回一部分字符,请使用 howmany 参数: "hello".split("", 3) //可返回 ["h", "e", "l"]
Example:
<html> <body> <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> </body> </html>
The above is the entire content of this article, I hope you all like it.