Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript split() method usage
split() method is used to split a string into an array of strings.
Syntax:
stringObject.split(separator,howmany)
Parameter description:
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 containing subexpressions, then the returned array includes strings matching those subexpressions (but not text matching 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:
1. Split the string in different ways
Result:
2. Split a string with a more complex structure
"2:3:4:5".split(":") //will return ["2", " 3", "4", "5"]"|a|b|c".split("|") //will return ["", "a", "b", "c"]
3. Split sentences into words
var words = sentence.split(' ')
Or use regular expressions as separator:
var words = sentence.split(/s+/)
4. If you want to split words as letters, or to split the string into characters, you can use the following code:
"hello".split("") // can return ["h", "e", "l", "l", " o"]
If you only need to return a part of the characters, please use the howmany parameter:
"hello".split("", 3) //Can return ["h", "e", "l"]