3

Is there any simple way to multiply alphanumeric string in jQuery / JS?

e.g

var str = "ABC";
console.log( str * 5 ); // this will nerutn `Nan`
// where what i want is `ABCABCABCABCABC`

Any suggestion much appreciated.

Iladarsda
  • 10,640
  • 39
  • 106
  • 170

5 Answers5

20

I see the exact question here:

Repeat String - Javascript

Just add this to your code:

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

var str = "ABC";
console.log( str.repeat(5) ); // this will return `ABCABCABCABCABC`
Community
  • 1
  • 1
Freesnöw
  • 30,619
  • 30
  • 89
  • 138
3

Try extending the String object with a prototype function.

String.prototype.repeat = function (n) {
    var str = '';
    for(var i = 0; i < n; i++) { str += this; }
    return str;
};

so that you can do it like this:

console.log(str.repeat(5));
Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66
0
String.prototype.duplicate = function( numTimes ){
  var str = "";
  for(var i=0;i<numTimes;i++){
      str += this;
  }
  return str;
};

console.log( "abc".duplicate(2) );

jsbin example

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

This returns Nan because str is not a number.

You should do like this :

var str = "ABC";
console.log( multiply(str,num) ); 

With the function

function multiply(str,num){
        for ( var int = 0; int < length; int++) {
         str += str;
        }
        return str
}
Jean-Charles
  • 1,690
  • 17
  • 28
0
String.prototype.multi = function(num) {
 var n=0,ret = "";
 while(n++<num) {
  ret += this;
 }
 return ret;
};

And then use .multi(5) on any string you want :) Like:

var s = "ABC";
alert( s.multi(5) );