TypeScript String split() Method

TypeScript String split() method is used to split a String object into an array of strings by separating the string into substrings.

Syntax

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

Parameters

  1. 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.

  2. limit − Integer specifying a limit on the number of splits to be found.

Return value

It 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);

Output

Simple split in TypeScript

Example 2: Splitting 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);

Output

[ 'The', 'quick', 'brown' ]

Example 3: Splitting 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);

Output

[ 'apple', 'banana', 'cherry', 'grape' ]

That’s it!