How to repeat string in JavaScript

repeat

The JavaScript repeat method allows us to repeat a string an n number of times.

The repeat method takes count (number of times the string is to be repeated) as an argument. The value can be a positive number between 0 and +Infinity.

The repeat method will return a new string that contains count (number of times the source string is to be repeated).

let loading = "loading ";
let dot = "." ;
let tenDot = dot.repeat(10);
console.log(loading + tenDot); // "loading .........."

In the above code, we have created ten . using the repeat method.

  • When we pass 0 as an argument we will get an empty string:
'.'.repeat(0)     // ''
  • When we pass a floating point number as an argument, the floating-point value is internally converted to integer:
'.'.repeat(2.5)   // '..' (2.5 will be converted to 2)
  • When the negative number is passed as an argument, we will get RangeError:
'.'.repeat(-1)    //RangeError: Invalid count value
  • When we pass Infifnity as an argument, we will get RangeError:
'.'.repeat(Infinity); //RangeError: Invalid count value

Code

console.log("Passing 0 to repeat method")
console.log( " Passing 0 will return empty string", '.'.repeat(0) );
console.log("\n---------\n")
console.log("Passing 2.5 to repeat method")
console.log( "Passing 2.5 will convert 2.5 to 2",'.'.repeat(2.5) );
console.log("\n---------\n")
// the be;ow code willl throw error
try {
console.log("Passing -1 to repeat method")
'.'.repeat(-1);
} catch(e){
console.log("We can't pass negative numbers to repeat method.", e.message);
}
console.log("\n---------\n")
try {
console.log("Passing Infinity to repeat method")
'.'.repeat(Infinity);
} catch(e){
console.log("We can't pass Infinity to repeat method", e.message);
}

Free Resources