![]() |
VOOZH | about |
The TypeScript split() method divides a string into an array of substrings using a specified separator, a string, or a regular expression. It optionally accepts a limit to determine the maximum number of splits. This method is commonly used for string manipulation.
string.split([separator][, limit])Parameter: This method accepts two parameters as mentioned above and described below:
limit (optional): An integer specifying the maximum number of splits to be found.Return Value: This method returns the new array.
In this example we are using the splits the string "Geeksforgeeks - Best Platform" into an array of words using the space character as a delimiter.
Output:
[ 'Geeksforgeeks', '-', 'Best', 'Platform' ]In this case, we split the string using a space as the separator.
Example: You can also limit the number of splits. For instance:
Output:
[
'G', 'e', 'e', 'k',
's', 'f', 'o', 'r',
'g', 'e', 'e', 'k',
's', ' '
]When using split(), be aware that consecutive separators in the original string can result in empty strings in the output array. To remove these empty strings, you can filter the array using filter(c => c).
Example:
Output:
[ 'Hello', 'World' ]Think beyond the basics! Consider scenarios like splitting URLs, parsing CSV data, or extracting keywords from a sentence.
Example - Splitting a URL:
Output:
[ 'https:', '', 'www.example.com', 'path', 'name', 'abc', 'age', '25' ]If you need to split by multiple separators (e.g., semicolon, colon, comma, newline), consider using a regular expression.
Example:
Output:
[ 'Hello', 'World', 'Welcome', 'To', 'TypeScript' ]