What is the string.repeat() method in TypeScript?

Overview

The repeat() method in TypeScript is used to return a new string a repeated number of times. This method is similar to JavaScript repeat() method. This is because anywhere that JavaScript runs, TypeScript runs too.

Syntax

string.repeat(n)
Syntax for repeat() method in TypeScript

Parameters

string: This is the string we want to return a number of times.

n: This represents how many times we want to return the specified string.

Return value

The value returned is a copy or copies of the number specified an n number of times.

Example

// create strings
let string1:string = "Edpresso"
let string2:string = "Is"
let string3:string = "The"
let string4:string = "Best!"
// print copies of this strings for some number of times
console.log(string1.repeat(4))
console.log(string2.repeat(3))
console.log(string3.repeat(2))
console.log(string4.repeat(1))

Explanation

  • Lines 2–5: We create some strings.
  • Lines 8–11: We print the strings some number of times to the console using the repeat() method.

Free Resources