TypeScript String split() Method
The split()
method in TypeScript allows you to split a string into an array of substrings by separating the string using a specified separator. It’s a method for handling string manipulation. In this article, we’ll learn the details of this method, and provide practical examples.
Syntax of String split() Method:
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.
Examples of String split() Method
1. Basic Usage:
Example: The below Simple example illustrates the String split() method in TypeScript.
JavaScript
<script>
var str = "Geeksforgeeks - Best Platform" ;
var newarr = str.split( " " );
console.log(newarr);
</script>
|
Output:
[ 'Geeksforgeeks', '-', 'Best', 'Platform' ]
In this case, we split the string using a space as the separator.
2. Specifying a Limit:
Example: You can also limit the number of splits. For instance:
JavaScript
<script>
var str = "Geeksforgeeks - Best Platform" ;
var newarr = str.split( "" ,14);
console.log(newarr);
</script>
|
Output:
[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ' ' ]
Here, we limit the splits to 14 characters.
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)
.
- Practical Use Cases: Think beyond the basics! Consider scenarios like splitting URLs, parsing CSV data, or extracting keywords from a sentence.
- Multiple Separators: If you need to split by multiple separators (e.g., semicolon, colon, comma, newline, etc.), consider using a regular expression. For example:
Javascript
const text = "a,c;d e\nx" ;
const splitted = text.split(/;|,| |\n/);
console.log(splitted);
|
Output
[ 'a', 'c', 'd', 'e', 'x' ]
Last Updated :
11 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...