JavaScript str_repeat
Returns the input string repeat mult times
1 2 3 4 56 7 8 9 1011 | function str_repeat (input, multiplier) { // Returns the input string repeat mult times // // version: 1109.2015 // discuss at: http://phpjs.org/functions/str_repeat // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // * example 1: str_repeat('-=', 10); // * returns 1: '-=-=-=-=-=-=-=-=-=-=' return new Array(multiplier + 1).join(input);} |
Examples
Running
1 | str_repeat('-=', 10); |
Should return
1 | '-=-=-=-=-=-=-=-=-=-=' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have str_repeat goodness in JavaScript.
I think that function has to be improved in this way:
return new Array(Number(multiplier)+1).join(input);
Change is in: Number(multiplier)
Explanation:
I have requirement for expanding numbers inside string in to equivalent number of characters. For example string: 3e2 must have string.length of 6
I have function that iterate through every character of a string and if is_numeric (one of phpjs functions too) replace that value with corresponding number of dummy characters using str_replace:
// max number that we can expand is 99
function expandTerm(subject) {
var output = '';
var repeat = '';
for (i=0; iif(is_numeric(subject[i])) {
repeat = subject[i];
if (is_numeric(subject[i + 1])) {
repeat = repeat * 10;
}
output = output + str_repeat('_', repeat);
repeat = '';
} else {
output = output + subject[i];
}
}
return output;
}
this returns 21 if input string is: 2 and __________01 if input string is: 10 and that is wrong. In first case output have to be: __ and in second __________ .
When I change your function, adding type casting on multiplier: Number(multiplier), everything working just as expected.
Have a nice day
This way it's faster :)
String.prototype.repeat = function(l){
return new Array(l+1).join(this);
};
alert("jonas".repeat(10));
@ Darell Brogdon: Thanks for pointing that out, I've searched hard, but wasn't able to find similar projects. Now that I did, how would you feel if I included some of your functions to this project? Well creditted of course.
Most functions are already here but I found a couple that would be a great addition.
The reason to continue here is I developed some tools that really help me to publish new functions quickly, and for me it would be a buzz killer to have to maintain this on sourceforge. Exposure here is bigger as well I think.
I do believe however that once php.js reaches version 1.0, housing it on such a platform would be a better idea.


أخبار بوابة نعم
Apr 4th