Home > Web Front-end > JS Tutorial > Summary of how to use split() in JavaScript_javascript tips

Summary of how to use split() in JavaScript_javascript tips

WBOY
Release: 2016-05-16 16:03:29
Original
1244 people have browsed it

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
Copy after login

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"]
Copy after login

Example 3

Use the following code to split sentences into words:

var words = sentence.split(' ')
//或者使用正则表达式作为 separator:
var words = sentence.split(/\s+/)
Copy after login

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"]
Copy after login

Example:

<html>
<body>
<script type="text/javascript">
var str="How are you doing today&#63;"
document.write(str.split(" ") + "<br />")
document.write(str.split("") + "<br />")
document.write(str.split(" ",3))
</script>
</body>
</html>
Copy after login

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template