String. prototype. repeat()
Returns a new string made up of the given number of copies of the original.
- Returns
- A new string containing
countcopies of the original. - Changes the original
- No
Example
#console.log('=-'.repeat(10))
console.log('β
'.repeat(4))
console.log('ha'.repeat(3))Definition and usage
#The repeat() method joins a string with itself as many times as you specify. "ab".repeat(3) gives "ababab", and repeat(0) returns an empty string.
It comes in handy for generating separators, indentation, simple progress bars, stars in ratings, or masking a piece of text. Instead of a loop that concatenates characters, a single call does the job.
The repeat count must be non-negative and finite. A negative value or Infinity throws a RangeError, and fractions are truncated, so 2.7 behaves like 2. The original stays unchanged.
Syntax
#string.repeat(count)Parameters
#count
number
The number of repetitions,0or higher. A fraction is truncated, and a negative or infinite value throws aRangeError.
More examples
#function progressBar(done, total) {
const filled = Math.round((done / total) * 10)
return 'β'.repeat(filled) + 'β'.repeat(10 - filled) + ` ${done}/${total}`
}
console.log(progressBar(3, 10))
console.log(progressBar(7, 7))const tree = [
['Course', 0],
['Module 1', 1],
['Lesson 1', 2],
['Module 2', 1]
]
for (const [label, depth] of tree) {
console.log(' '.repeat(depth * 2) + label)
}console.log('ab'.repeat(2.7))
console.log('ab'.repeat(0).length)
try {
'ab'.repeat(-1)
} catch (error) {
console.log(error.name)
}Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- A repeat count calculated from data, such as
10 - filled, can end up negative. Guard it withMath.max(0, n)to avoid aRangeError. - A very large repeat count creates a huge string and can freeze the page. The engine also has an upper limit on string length.
Related entries
#- String.prototype.padStart()Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- String.prototype.padEnd()Pads a string on the right with the given text until it reaches the specified length.
- Template literalsText templates in backticks: insert values with ${} and span multiple lines.
- Array.prototype.fill()Fills an array (or part of it) with a single value.
Spotted a mistake or missing an example? Write to us.