先来看下面这段代码:
1 2 3 4 5 6 <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>输出结果如下:
1 2 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范例:
1 2 "2:3:4:5".split(":") //将返回["2", "3", "4", "5"] "|a|b|c".split("|") //将返回["", "a", "b", "c"]使用下面的代码,可以把句子分割成单词:
1 var words = sentence.split(' ')如果您希望把单词分割为字母,或者把字符串分割为字符,可使用下面的代码:
1 "hello".split("") //可返回 ["h", "e", "l", "l", "o"]若只需要返回一部分字符,请使用 howmany 参数:
1 "hello".split("", 3) //可返回 ["h", "e", "l"]或者使用正则表达式作为 separator:
1 var words = sentence.split(/s+/)