To split a String in TypeScript, you can use String.split() function. The syntax of the split method is provided below:

mystring.split([separator][, limit]);

where mystring is split into limit number of splits with separator as delimiter.

Basic Example to Split String in TypeScript

In this example, we will split the string with separator passed as argument.

example.ts

var str = new String("Apple--Basket--Share--Options") 
var splits = str.split("--")
console.log(splits)

Convert this to JavaScript

tsc example.ts

example.js

var str = new String("Apple--Basket--Share--Options");
var splits = str.split("--");
console.log(splits);

Run it on a browser.

TypeScript Split String example
ADVERTISEMENT

Split String with a limit on the number of splits

In this example, we will split the string with separator and also the number of splits passed as arguments.

example.ts

var str = new String("Apple--Basket--Share--Options") 
var splits = str.split("--", 3)
console.log(splits)

Convert this to JavaScript

tsc example.ts

example.js

var str = new String("Apple--Basket--Share--Options");
var splits = str.split("--", 3);
console.log(splits);

Run it on a browser.

TypeScript Split String with Limited Splits