The String.split() method in JavaScript is used to divide a string into an array of substrings. While it is often used with simple delimiters like spaces or commas, you can use Regular Expressions (RegEx) for more advanced and flexible string splitting.
Syntax
string.split(separator, limit)
- separator: This can be a string or a regular expression that defines where to split the string.
- limit: (Optional) Specifies the maximum number of substrings to include in the array.
1. Split on a Single Character
Output[ 'apple', 'banana', 'cherry' ]
- The regular expression /-/ matches the hyphen (-) in the string.
- The string is split at each occurrence of the hyphen.
2. Split on Multiple Delimiters
Output[ 'apple', ' banana', ' cherry', 'grape' ]
- The regular expression /[,;|]/ matches commas, semicolons, or vertical bars.
- The string is split at each occurrence of any of these characters.
3. Split and Remove Extra Whitespace
Output[ '', 'apple', 'banana', 'cherry', '' ]
- \s+: Matches one or more whitespace characters.
- The string is split at spaces, tabs, or newlines.
4. Split by Word Boundaries
Output[ 'Hello', 'World' ]
- (?=[A-Z]): Matches a position before any uppercase letter.
- The string is split into "Hello" and "World" based on word boundaries.
5. Split and Keep the Delimiters
Output[ 'one', ',', ' two', ';', ' three' ]
- ([,;]): Captures the delimiters (commas and semicolons) using parentheses.
- The captured delimiters are included in the resulting array.
6. Limit the Number of Splits
Output[ 'apple', 'banana' ]
- The limit argument restricts the output to 2 substrings.
- The string is split at the first two occurrences of the hyphen.
7. Split on Digits
Output[ 'apple', 'banana', 'cherry', 'grape' ]
- \d: Matches any digit (0–9).
- The string is split at every digit.
8. Split on a Custom Pattern (Email Example)
Output[ 'username', 'gmail', 'com' ]
- [@.]: Matches the "@" symbol or a period.
- The email is split into its username, domain, and extension.
9. Remove Empty Strings in the Result
If splitting leaves empty strings, you can filter them out.
Output[ 'apple', 'banana', 'cherry' ]
- /,+/: Matches one or more commas.
- .filter(Boolean): Removes empty strings from the resulting array.
10. Split Multiline String