Repeat a string in JavaScript a number of times
These days, the repeat
string method is implemented almost everywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:
"a".repeat(10)
Before repeat
, we used this hack:
Array(11).join("a") // create string with 10 a's: "Repeat String - JavaScriptaa"
(Note that an array of length 11 gets you only 10 "a"s, since Array.join
puts the argument between the array elements.)
Simon also points out that according to this benchmark, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).
Repeat String - Javascript
Good news! String.prototype.repeat
is now a part of JavaScript.
"yo".repeat(2);
// returns: "yoyo"
The method is supported by all major browsers, except Internet Explorer. For an up to date list, see MDN: String.prototype.repeat > Browser compatibility.
MDN has a polyfill for browsers without support.
How can I recurse in JS to repeat a string n times?
Recursion involves making a function call itself and AVOIDS using a loop. You have a loop in the recursive function which is a big red flag.
Do something like this:
If n is 1 return s else return s concatenated to the result of the function with n - 1.
function repeatStr (n, s) {
if (n == 1)
return s;
else
return s.concat(repeatStr(n - 1, s))
}
repeatStr(3, "Hi")
How can I repeat strings in JavaScript?
There is no such function, but hey, you can create it:
String.prototype.repeat = function(times) {
return (new Array(times + 1)).join(this);
};
Usage:
var s = " ".repeat(3);
Of course you could write this as part of a standalone group of functions:
var StringUtilities = {
repeat: function(str, times) {
return (new Array(times + 1)).join(str);
}
//other related string functions...
};
Usage:
var s = StringUtilities.repeat(" ", 3);
how to repeat string in javascript loop
a bit clean way Repeat function
const repeatString = function(str, num) {
return (num < 0) ? new Error("Error") : str.repeat(num);
}
module.exports = repeatString
how can i repeat a string multiple times according to its index in a string
In functional style (thanks to @Redu for the comment):
const accum = (s) => Array.from(
s,
(c, i) => `${c.toLocaleUpperCase()}${c.repeat(i)}`
)
.join('-');
console.log(accum(''));
console.log(accum('a'));
console.log(accum('xyz'));
Simple way to repeat a string
String::repeat
". ".repeat(7) // Seven period-with-space pairs: . . . . . . .
New in Java 11 is the method String::repeat
that does exactly what you asked for:
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
Its Javadoc says:
/**
* Returns a string whose value is the concatenation of this
* string repeated {@code count} times.
* <p>
* If this string is empty or count is zero then the empty
* string is returned.
*
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*
* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/
Related Topics
How to List the Properties of a JavaScript Object
JavaScript: Difference Between .Foreach() and .Map()
Correct Try...Catch Syntax Using Async/Await
Generate a Hash from String in JavaScript
How to Write a Countdown Timer in JavaScript
JavaScript Inheritance and the Constructor Property
Sleep in JavaScript - Delay Between Actions
Persistent Service Worker in Chrome Extension
How to Simulate a Click With JavaScript
Jquery Scroll() Detect When User Stops Scrolling
Rails 4: Disable Turbolinks in a Specific Page
Is "Monkey Patching" Really That Bad
Rails 4 Turbolinks Make Form Submit Multiple Times
How to Execute JavaScript in Ruby Written Webdriver Test
Problem Deploying Rails 3.1 Project to Heroku: Could Not Find a JavaScript Runtime