JavaScript – Repeat a String for N Times
To repeat a given string N times in JavaScript, use a looping statement like For loop or While Loop to iterate for N times, and concatenate the resulting string with the given string for N times.
The sample code to repeat a given string str
for N
times using For Loop and store the output in result
is
</>
Copy
var result = "";
var N = 4;
for (let i=0; i < N; i++) {
result += str;
}
Example
In the following example, we take a string str
, repeat it for N times using For loop, and display the original and resulting string in pre#output.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var str = 'apple';
var result = "";
var N = 4;
for (let i=0; i < N; i++) {
result += str;
}
var output = 'Original string : ' + str;
output += '\n\nResult string : ' + result;
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to repeat given string for N times in JavaScript, with examples.