SoFunction
Updated on 2025-04-05

JavaScript split usage method and example

Split definition and usage
The split() method is used to split a string into a string array.
grammar
(separator, howmany) Parameter Description
separator required. A string or regular expression that splits stringObject from where this parameter specifies.
howmany optional. This parameter specifies the maximum length of the returned array. If this parameter is set, the returned substrings will not be more 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
An array of strings. This array is created by splitting the string stringObject into substrings at the boundary specified by separator. The string in the returned array does not include the separator itself.
However, if separator is a regular expression containing subexpressions, the returned array includes a string matching those subexpressions (but not text matching the entire regular expression).
Tips and comments
Note: If an empty string ("") is used as a separator, each character in the stringObject will be split between.
Note: The action performed is the opposite of the action performed.
In this example, we will split the string in different ways:

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

Output:
Copy the codeThe code is 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 examples
In this example, we will split the more complex string:
"2:3:4:5".split(":")   //It will return ["2", "3", "4", "5"]
"|a|b|c".split("|")    //It will return ["", "a", "b", "c", ""]
Example 3
Use the following code to split sentences into words:
var words = (' ') or use regular expressions as separator:
var words = (/\s+/) Example 4
If you want to split a word into letters, or split a string into characters, 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"]

I won't say much about the usage of js split. Let me give you an example.

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

The output result is
Copy the codeThe code is as follows:

2
2
3
5
6
6

js split is to split a string into multiple strings with specific characters, and you should understand it at a glance.