Answered
Using JavaScript, how can I create function or method that takes a string and repeats it a variable number of times.
For instance, it should take this string:
"abcd"
And convert it to this:
"abcdabcdabcd"
Thanks in advance!
You can use the ES6 repeat() method:
string.repeat(3);
That will take your string and repeat it i
times. In this case, 3
times.
This is an ES6 feature, so make sure you check browser compatibility before using it in a website.
Here's a function you can use:
function repeatString(string, times) {
let repeatedString = "";
while (times > 0) {
repeatedString += string;
times --;
}
return repeatedString;
};
To repeat your string 3
times, use the function like this:
repeatString("abcd", 3); // "abcdabcdabcd"
Using a for
loop:
const num = 3;
const str = "abcd";
let newString = "";
for (let i = 0; i < num; i++) {
newString += str;
}
// newString = "abcdabcdabcd"