Home  >  Article  >  Web Front-end  >  How to use split() method

How to use split() method

藏色散人
藏色散人Original
2020-04-18 10:23:565216browse

How to use split() method

How to use the split() method?

JavaScript split() method

JavaScript String object

Recommended: "javascript Advanced Tutorial"

Definition and Usage

The split() method is used to split a string into a string array.

Syntax

stringObject.split(separator,howmany)

Parameters

separator required. A string or regular expression to split the stringObject from where specified by this parameter.

howmany Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings will be returned than the array specified by this parameter. If this parameter is not set, the entire string will be split regardless of its length.

Return value

A string array. The array is created by splitting the string stringObject into substrings at the boundaries specified by separator. The strings in the returned array do not include the separator itself.

However, if separator is a regular expression that contains subexpressions, the returned array includes strings that match those subexpressions (but not text that matches the entire regular expression).

Tips and Notes

Note: If the empty string ("") is used as a separator, each character in the stringObject will be split between them.

Note: The operation performed by String.split() is the opposite of the operation performed by Array.join.

Example

Example 1

In this example, we will split the string in different ways:

<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>

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 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"]

Example 3

Using the following code, the sentence can be Split into words:

var words = sentence.split(&#39; &#39;)

Or use regular expression as separator:

var words = sentence.split(/\s+/)

Example 4

If you want to split words into letters, or split strings into characters , you can 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"]

The above is the detailed content of How to use split() method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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