Example of the string splitting function split in JavaScript
- 2020-05-27 04:14:26
- OfStack
This article illustrates the use of the string splitting function split in JavaScript as an example. Share with you for your reference. The details are as follows:
Let's look at this code first:
<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(":") // Will return ["2", "3", "4", "5"]
"|a|b|c".split("|") // Will return ["", "a", "b", "c"]
You can split a sentence into words using the following code:
var words = sentence.split(' ')
If you want to split a word into letters, or a string into characters, use the following code:
"hello".split("") // Can be returned ["h", "e", "l", "l", "o"]
If you only need to return 1 part of the characters, please use the howmany parameter:
"hello".split("", 3) // Can be returned ["h", "e", "l"]
Or use regular expressions as separator:
var words = sentence.split(/\s+/)
I hope this article is helpful for you to design javascript program.