TypeScript String split() method is “used to split a String object into an array of strings by separating the string into substrings.”
separator − Specifies the character to use for separating the string. If the separator is omitted, the array returned contains one element of the entire string.
limit − Integer specifying a limit on the number of splits to be found.
The split() method returns the new array. When the string is empty, Split returns an array containing one empty string rather than an empty array.
Example 1: Simple split
let str: string = "Hello World"; let result: string = str.split(" "); console.log(result);
Example 2: Split with a Limit
You can also specify a limit to the number of splits. This example will split the string by spaces, but it will stop after 2 splits.
let str: string = "The quick brown fox jumps over"; let result: string = str.split(" ", 3); console.log(result);
[ 'The', 'quick', 'brown' ]
Example 3: Split Using a Regular Expression
This example will split a string by either a comma or a space.
let s: string = "apple,banana cherry,grape"; let r: string = s.split(/[\s,]+/); console.log(r);
[ 'apple', 'banana', 'cherry', 'grape' ]