JavaScript - Repeat String



Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number.


Solution 1 using for-loop


console = { 
    log: print,
    warn: print,
    error: print
};
function repeatStringNumTimes(str, num) {
    var newStr = "";
    for (var i = 0; i < num; i++) {
        newStr += str;
    }
    return newStr;
}
console.log(repeatStringNumTimes("abc", 3));

Output:


abcabcabc

Solution 2 using while-loop


console = { 
    log: print,
    warn: print,
    error: print
};
function repeatStringNumTimes(str, num) {
    var accumulatedStr = "";

    while (num > 0) {
        accumulatedStr += str;
        num--;
    }
    return accumulatedStr;
}
console.log(repeatStringNumTimes("abc", 3));

Output:


abcabcabc

Solution 3 Ternary Recursion


console = { 
    log: print,
    warn: print,
    error: print
};
function repeatStringNumTimes(str, num) {

    return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}
console.log(repeatStringNumTimes("abc", 3));

Output:


abcabcabc

Solution not working or have any suggestions? Please send an email to [email protected]



Join Our Facebook Group


Share this example


Download Android App

download android app

Popular javascript Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube