I want to create a string by concatenating multiple copies of another in CoffeeScript or JavaScript.
Do I have to create my own function for this or is there a shortcut like in Python?
I want to create a string by concatenating multiple copies of another in CoffeeScript or JavaScript.
Do I have to create my own function for this or is there a shortcut like in Python?
You could use this shortcut (need to pass the number of repetitions plus 1):
Array(6).join 'x'
This is coming in the next version of ECMAScript, so you might as well implement it as a shim.
http://wiki.ecmascript.org/doku.php?id=harmony:string.prototype.repeat
From the proposal:
Object.defineProperty(String.prototype, 'repeat', {
value: function (count) {
var string = '' + this;
//count = ToInteger(count);
var result = '';
while (--count >= 0) {
result += string;
}
return result;
},
configurable: true,
enumerable: false,
writable: true
});
Then call .repeat()
from a string:
"x".repeat(5); // "xxxxx"
You can use array.join(JavaScript). Array()
function extend(ch, times){
return Array(times+1).join('x');
}
extend('x', 5);