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.
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.
I see the exact question here:
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`
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));
String.prototype.duplicate = function( numTimes ){
var str = "";
for(var i=0;i<numTimes;i++){
str += this;
}
return str;
};
console.log( "abc".duplicate(2) );
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
}
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) );