Table of Contents Hide
split() method with examples.
split() method splits a string into an ordered list of strings and returns them as an array.
split() method is as follows.
str is the string or the string variable.
split() method takes two parameters, and both are optional.
1) separator (Optional) – The separator determines where the split needs to happen in a given string. The separator can be a single character, a substring, or it can be a regular expression.
If you do not specify the separator, then by default, the entire string is returned as-is.
2) limit (Optional) – A limit is a non-negative number that specifies the number of substrings it needs to split into.
If the limit is 0, the
split() method returns an empty array.
split() Return Value
split() method splits the string at each point where the separator matches and returns an array of substrings.
- If separator is found, the separator is removed from the string, and the substrings are returned in an array.
- If the separator is an array, then that Array is restricted to a String and used as a separator.
split()method does not change the original string.
In the following example, we use the
split() method to split the string into words. If the string and separator are empty, the method returns an empty array, as shown below.
If you want to split the string into an array of characters, you can just pass an empty delimiter, as shown below.
Note: It is not recommended to use the split() method to split the string into an array as we get improper results with non BMP(non-Basic-Multilingual-Plane) character sets. The methods like .split() and .charCodeAt() only respect the characters with a code point below 65536. The higher code points are represented by a pair of (lower valued) “surrogate” pseudo-characters.
// split the text into array of chars using empty string console.log("ABCDEFGHIJK".split('')); // split the text into array of chars using empty string and limit to 3 chars console.log("ABCDEFGHIJK".split('', 3));
['A', 'B', 'C', 'D','E', 'F', 'G', 'H','I', 'J', 'K'] [ 'A', 'B', 'C' ]
separator is a regular expression that contains capturing parentheses
(``), matched results are included in the array as shown below.
\d matches the character class for digits between 0 and 9.
const sampleText = "Hello 1 World 2 !!!" console.log(sampleText.split(/(\d)/))
[ 'Hello ', '1', ' World ', '2', ' !!!' ]