split() function splits a string into an array according to the specified delimiter. Usage: result = string.split(separator, limit), where separator is the separator and limit is the optional limit on the number of elements (no limit by default). Returns an array containing substrings, delimited by characters, regular expressions, or strings. If delimiter is empty, each character becomes an element. If the delimiter is not in the string, returns a single-element array containing the entire string. limit controls the number of elements in the returned array.
Usage of split function in JS
split()
The function is a built-in JavaScript Function that splits a string into an array using a specified delimiter. It is widely used in string processing and text parsing.
Usage:
<code>var result = string.split(separator, limit);</code>
Where:
: The string to be split.
: The separator used to split the string.
(optional): The maximum number of array elements after splitting. By default,
limit is
Infinity, which means the string will be split into any number of elements.
Return value:
split() The function returns an array containing substrings. If no delimiter is specified, the function uses the space character as the default delimiter.
Example:
<code>const str = "Hello, World!"; // 按逗号分隔字符串 const result1 = str.split(","); // ["Hello", " World!"] // 按空格分隔字符串,限制为 2 个元素 const result2 = str.split(" ", 2); // ["Hello,", "World!"]</code>
Note:
function will return a single-element array containing the entire string. The
parameter allows controlling the number of elements in the split array. If
limit is less than the number of occurrences of the delimiter in the string, the returned array will contain
limit elements and the remainder will be discarded.
The above is the detailed content of How to use split function in js. For more information, please follow other related articles on the PHP Chinese website!