totn JavaScript

JavaScript: String repeat() method

This JavaScript tutorial explains how to use the string method called repeat() with syntax and examples.

Description

In JavaScript, repeat() is a string method that is used to repeat a string a specified number of times. Because the repeat() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the repeat() method is:

string.repeat([count]);

Parameters or Arguments

count
Optional. The number of times to repeat the string. If this parameter is not provided, the repeat() method will use 0 as the default and return an empty string.

Returns

The repeat() method returns a string that has been repeated a desired number of times.

If the count parameter is not provided or is a value of 0, the repeat() method will return an empty string. If the count parameter is a negative value, the repeat() method will return RangeError.

Note

  • The repeat() method does not change the value of the original string.

Example

Let's take a look at an example of how to use the repeat() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.repeat(0));
console.log(totn_string.repeat(1));
console.log(totn_string.repeat(2));
console.log(totn_string.repeat(3));

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the repeat() method of the totn_string variable to repeat the string a specified number of times.

We have written the output of the repeat() method to the web browser console log, for demonstration purposes, to show what the repeat() method returns.

The following will be output to the web browser console log:

<empty string>
TechOnTheNet
TechOnTheNetTechOnTheNet
TechOnTheNetTechOnTheNetTechOnTheNet

As you can see, the repeat() method returned an empty string when the count parameter was 0, Otherwise, it repeated the string 'TechOnTheNet' the specified number of times.