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.

6
  • I'd go so far as to say definite duplicate. There are some good answers in the older thread. Commented Oct 4, 2011 at 12:31
  • 1
    @Dade, use the close link in the post to link to duplicates. Commented Oct 4, 2011 at 12:35
  • @epascarello It isn't showing a close link. Commented Oct 4, 2011 at 12:37
  • @Dade, you need more rep I guess! :) Commented Oct 4, 2011 at 14:40
  • @epascarello Odd, I see the delete link on all of the other pages though...... Commented Oct 4, 2011 at 14:52

5 Answers 5

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`
Sign up to request clarification or add additional context in comments.

2 Comments

this looks way cleaner, and makes for creative use of Array.join. :D +1!
Thread should be closed as a dupe.
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));

Comments

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

Comments

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
}

Comments

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) );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.