String repeat()
In JavaScript, String.repeat() method is used to repeat the string by a given number of times.
Syntax
str.repeat(count)
where
str
is a stringrepeat
is function namecount
is an integer
repeat()
method repeats the string str
by count
number of times, and returns the resulting string. repeat()
does not modify the original string str
.
Examples
1. Repeat the string 4 times.
let str = 'apple';
let output = str.repeat(4);
console.log('Output : ' + output);
2. If n
is 0
, then repeat() returns an empty string.
let str = 'apple';
let output = str.repeat(0);
console.log('Output : ' + output);
3. If n
is a negative value, then repeat() raises RangeError
.
let str = 'apple';
let output = str.repeat(-3);
console.log('Output : ' + output);