1

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?

phant0m
  • 16,133
  • 5
  • 45
  • 81
mavix
  • 2,408
  • 6
  • 26
  • 48

3 Answers3

4

You could use this shortcut (need to pass the number of repetitions plus 1):

Array(6).join 'x'
Justin Niessner
  • 236,029
  • 38
  • 403
  • 530
3

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"
I Hate Lazy
  • 45,169
  • 12
  • 84
  • 76
0

You can use array.join(JavaScript). Array()

function extend(ch, times){

    return Array(times+1).join('x');
}
 extend('x', 5);
Anoop
  • 22,496
  • 10
  • 60
  • 70