Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Repeat String in JavaScript?
JavaScript provides multiple ways to repeat a string. The most modern approach is using the built-in repeat() method, but you can also use older techniques like Array.join().
Using String.repeat() (Recommended)
The String.repeat() method is the standard way to repeat strings in modern JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>String Repeat Example</title>
</head>
<body>
<script>
let str = "Hello ";
let repeated = str.repeat(3);
console.log(repeated);
// More examples
console.log("*".repeat(10));
console.log("ABC".repeat(4));
</script>
</body>
</html>
Hello Hello Hello ********** ABCABCABCABC
Using Array.join() Method
Before repeat() was available, developers used Array.join() to repeat strings:
<!DOCTYPE html>
<html>
<head>
<title>Array Join Repeat</title>
</head>
<body>
<script>
function repeatString(str, count) {
return new Array(count + 1).join(str);
}
console.log(repeatString("Hello ", 3));
console.log(repeatString("-", 8));
</script>
</body>
</html>
Hello Hello Hello --------
Extending String Prototype
You can extend the String prototype to add a custom repeat method:
<!DOCTYPE html>
<html>
<head>
<title>String Prototype Extension</title>
</head>
<body>
<script>
String.prototype.repeatTimes = function(count) {
return new Array(count + 1).join(this);
};
console.log("Hi ".repeatTimes(4));
console.log("=".repeatTimes(15));
</script>
</body>
</html>
Hi Hi Hi Hi ===============
Comparison
| Method | Browser Support | Performance | Readability |
|---|---|---|---|
String.repeat() |
ES6+ (Modern) | Best | Excellent |
Array.join() |
All browsers | Good | Moderate |
| Prototype extension | All browsers | Good | Good |
Common Use Cases
<!DOCTYPE html>
<html>
<head>
<title>Practical Examples</title>
</head>
<body>
<script>
// Creating separators
console.log("=".repeat(30));
// Padding strings
let num = "42";
let padded = "0".repeat(5 - num.length) + num;
console.log(padded);
// Creating patterns
console.log("*-".repeat(10));
</script>
</body>
</html>
============================== 00042 *-*-*-*-*-*-*-*-*-*-
Conclusion
Use String.repeat() for modern applications as it's cleaner and more efficient. Fall back to Array.join() only when supporting very old browsers.
Advertisements
