What is string.split() in TypeScript?

Overview

Just as in JavaScript, which is a subset of TypeScript, the split() method exists. This method splits a string into an array of its substrings. All it needs is a separator that tells how to split the string into substrings.

Syntax

string.split(separator,[limit])
Syntax for split() method in TypeScript

Parameters

separator: This tells TypeScript where to start splitting the string.

limit: This is the limit of elements of the array returned. It is the number of elements we want to see returned.

Return value

The value returned is an array.

Example

export {}
// create some strings
let greeting:string = "Welcome to Edpresso"
let fruits:string = "Apple, Orange, Mango, Banana"
let numbers:string = "one-two-three-four-five"
let url:string = "https://www.educative.io/index.html"
// split the strings to arrays
let split1 = greeting.split(" ");
let split2 = fruits.split(",")
let split3 = numbers.split("-", 2) // return just 2 elements
let split4 = url.split(".")
// print the arrays
console.log(split1)
console.log(split2)
console.log(split3)
console.log(split4)

Explanation

  • Line 1: We export our file as a module.
  • Lines 4–7: We create some strings.
  • Lines 10–13: We split the strings we created into arrays.
  • Lines 16–19: We print the arrays to the console.

Free Resources