In JavaScript split of USES method summary

  • 2020-05-30 19:24:27
  • OfStack

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))
// Output: 
//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 case, we'll split the more complex string:


"2:3:4:5".split(":") // Will return ["2", "3", "4", "5"]
"|a|b|c".split("|") // Will return ["", "a", "b", "c"]

Example 3

You can split a sentence into words using the following code:


var words = sentence.split(' ')
// Or use regular expressions as  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("") // Can be returned  ["h", "e", "l", "l", "o"]
// If you just need to return 1 Partial character, please use  howmany  Parameters: 
"hello".split("", 3) // Can be returned  ["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>

That's all for this article, I hope you enjoy it.


Related articles: