Split in TypeScript

Find this useful? Support us: Star on GitHub 6
Category: String | Language: TypeScript

To split a string in TypeScript, you can use the split() method which returns an array containing the substrings generated by splitting the original string using the specified separator. Here's an example:

let myString = "Hello, world!";
let myArray = myString.split(", "); // split the string at the comma and space
console.log(myArray); // Output: ["Hello", "world!"]

In the example above, split() method splits the string into two substrings at the comma and space, and returns them as an array. The resulting array contains the substrings "Hello" and "world!".

You can also split a string based on a regular expression. Here's an example:

let myString = "watermelon, apple, banana, pear";
let myArray = myString.split(/,\s+/); // split the string at each comma followed by one or more spaces
console.log(myArray); // Output: ["watermelon", "apple", "banana", "pear"]

In this example, split() method splits the string using the regular expression /,\\s+/, which matches each comma followed by one or more spaces. The resulting array contains the substrings "watermelon", "apple", "banana", and "pear".