[Javascript] Replicate a string (code example)

Mike Dougherty mdougherty at pbp.com
Fri Jul 1 19:17:12 CDT 2005


Someone was just asking in IRC how to replicate a string, which reminded me of the following code 
example.  It uses bitwise operators to control the iteration of multiple additions.  The code is 
unintuitive, but if you examine it in a console you will see how efficient it is.  I thought I'd 
share in case anyone else has a use for a REPLicate function.  ( I didn't write it, but could not 
find this example using google either )

/* REPLicate a string (s) some number of times (n) */
function repl(s,n) {
   var r='';
   while(n) {
     if(n&1) {r+=s;}
     s+=s;
     n>>=1;
     }
   return r;
   }



More information about the Javascript mailing list