The example in this article describes the usage of the string splitting function split in JavaScript. Share it with everyone for your reference. The details are as follows:
First look at the following code:
<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>
The output results are as follows:
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:3:4:5".split(":") //将返回["2", "3", "4", "5"] "|a|b|c".split("|") //将返回["", "a", "b", "c"]
Use the following code to split sentences into words:
var words = sentence.split(' ')
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"]
If you only need to return a part of the characters, please use the howmany parameter:
"hello".split("", 3) //可返回 ["h", "e", "l"]
Or use regular expression as separator:
var words = sentence.split(/\s+/)
I hope this article will be helpful to everyone’s JavaScript programming design.