API
@-Formulas
JavaScript
LotusScript
Reg Exp
Web Design
Notes Client
XPages
 
Repeat String
I recently had a need to repeat a string using JavaScript. I'm sure there are other ways to do this, but at the time I couldn't find anything good on the internet to do it (maybe I wasn't searching for the right stuff). This function will take a string and repeats it "x" times, up to a maximum length.

Please note... if you have purchased the Reusable Object Library Level 2 application, you can use the "Find New Reusable Objects" feature to quickly download this design element and it's associated documentation at no cost.

Here is the function information:

Function Name: repeat
Function Description: take an input string and duplicate it as many times as desired, up to a maximum number of characters
Parameters: string = string to be repeated, integer = number of times to repeat, integer = total number of characters to return
Returns: string = repeated string

Here is the actual function:

function repeat(repeatString, repeatNum, returnNum) {
    var newString = "";
    returnNum += "";
    if (returnNum == "undefined" || returnNum == "0") { return ""; }
    for (var x=1; x<=parseInt(repeatNum, 10); x++) {
        newString = newString + repeatString;
    }
    if (newString == "") {
        return (newString);
    } else {
        return (newString.substring(0, parseInt(returnNum, 10)));
    }
}

The function is pretty straightforward. It first defines the string to be returned. It then makes sure that the third parameter is a valid amount by converting it to a string. If the third parameter is 0, then there will be no length for the return string, so an empty string is returned. Then the code loops repeatNum times and continually appends the string to be repeated. When finished looping, the string is shortened to the right length and returned. Note that if the string is empty (if the repeatString parameter was an empty string) then there is no way to get a substring, so that's why the extra check is made.