TypeScript String split() Method
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.
Syntax
string.split([separator][, limit])
Parameter: This method accepts two parameters as mentioned above and described below:
- separator – The character used for separating the string. It can be a regular expression or a simple string.
limit
(optional): An integer specifying the maximum number of splits to be found.
Return Value: This method returns the new array.
Example 1: Basic Usage:
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.
const str: string = "Geeksforgeeks - Best Platform";
const result: string[] = str.split(" ");
console.log(result);
Output:
[ 'Geeksforgeeks', '-', 'Best', 'Platform' ]
In this case, we split the string using a space as the separator.
Example 2: Specifying a Limit
Example: You can also limit the number of splits. For instance:
// Original string
let str: string = "Geeksforgeeks - Best Platform";
// Use of String split() Method
let newarr: string[] = str.split("", 14);
console.log(newarr);
Output:
[
'G', 'e', 'e', 'k',
's', 'f', 'o', 'r',
'g', 'e', 'e', 'k',
's', ' '
]
Additional Tips of String Spit() Method
Handling Empty Strings
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:
const str: string = "Hello,,World";
const result: string[] = str.split(",").filter((c: string) => c !== "");
console.log(result);
Output:
[ 'Hello', 'World' ]
Practical Use Cases
Think beyond the basics! Consider scenarios like splitting URLs, parsing CSV data, or extracting keywords from a sentence.
Example – Splitting a URL:
const url: string = "https://www.example.com/path?name=abc&age=25";
const parts: string[] = url.split(/[/?&=]/);
console.log(parts);
Output:
[ 'https:', '', 'www.example.com', 'path', 'name', 'abc', 'age', '25' ]
Multiple Separators
If you need to split by multiple separators (e.g., semicolon, colon, comma, newline), consider using a regular expression.
Example:
const str: string = "Hello;World:Welcome,To\nTypeScript";
const result: string[] = str.split(/[\s,;:]+/);
console.log(result);
Output:
[ 'Hello', 'World', 'Welcome', 'To', 'TypeScript' ]