How to repeat a string n number of times in JavaScript


Here, we will learn how to repeat a string n times using a JavaScript inbuilt function ( repeat() ) and also code a custom function to do the repeat task.

What is repeat() function in JavaScript?

The repeat() is an inbuilt JavaScript function that return a string containing a specific number of copies for which the repeat() function was called.

SYNTAX:

string.repeat(count)

count : It is an integer value which specifies how many copies you want of the string.

EXAMPLE:

let str = 'world'
let repStr = str.repeat(3)
console.log(repStr)

//OUTPUT
//'worldworldworld'

Code a custom repeat function in JavaScript

You can also create a custom repeat function to repeat a given string for a specific number too.

function repeat( str,count ){
  newString = '';
  
  while(count){
    newString += str;
    count--;
  }
  
  return newString;
  
 }

var newStr = repeat('world', 3)

console.log(newStr)

OUTPUT:

worldworldworld

Here i am using the while loop inside the function with two argument: str (the string) and count (no. of time we want to repeat the string). And the while loop will run till the count becomes 0 and then the function will return us the new String.


💾 Recommended Articles