JavaScript string repeat

In this blog we will learn how can we repeat string in JavaScript.

JavaScript string have have inbuild repeat() function. which allows as to repeat a string number of times.

String.prototype.repeat()

This function returns a new string with a specified number of copies of the string it was called on.

Syntax

stringObject.repeat(count)

Here count is required parameter which is use to repeat string number of times. It's value can be 0 to +Infinity.

Example

var stringObject = "Hello! I am Sourabh Somani... ";

repeatedString = stringObject.repeat(5);
//Output
//"Hello! I am Sourabh Somani... Hello! I am Sourabh Somani... Hello! I am Sourabh Somani... Hello! I am Sourabh Somani... Hello! I am Sourabh Somani... "

Note

In repeat() function the count value which we are passing that can be only in 0 to +Infinity. If we provide value apart from this then this function can throw error. Examples are as follows

'Hello'.repeat(-5) // This throw RangeError "Uncaught RangeError: Invalid count value"

'Hello'.repeat(0) // '' (This will return empty string)

'Hello'.repeat(2.5) // 'HelloHello' If Count value is float then it will be converted into integer

//Any string which cannot be convert into Number
'Hello'.repeat("anystring") // ''

//If string Number 
'Hello'.repeat("3") //'HelloHelloHello'

//NaN and Undefined Returns Empty String 
'Hello'.repeat(NaN) // ''
'Hello'.repeat(Undefined) // ''

'Hello'.repeat(1/0) // This throw RangeError "Uncaught RangeError: Invalid count value"

😊😊😊

Sourabh Somani
He is Microsoft MVP & C# Corner MVP. His core competencies include Mobile and web applications development using .NET, Python, Node.js, C#, JavaScript, jQuery, SQL Server, NoSQL, MongoDB, and Angular.
Chittorgarh, Rajasthan, India