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,595
  • 5
  • 50
  • 82
mavix
  • 2,488
  • 6
  • 30
  • 52

3 Answers3

4

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

Array(6).join 'x'
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
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
  • 47,415
  • 13
  • 86
  • 77
0

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

function extend(ch, times){

    return Array(times+1).join('x');
}
 extend('x', 5);
Anoop
  • 23,044
  • 10
  • 62
  • 76