0

Is there a way using JavaScript's RegEx engine to convert

"2" -> "HelloHello"?

"3" -> "HelloHelloHello" ?

NoodleFolk
  • 1,701
  • 1
  • 12
  • 23

4 Answers4

1
"Hello".repeat(2);

This is new! Not available in some browsers!!!! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat It is perfect if you're working an environment that supports it, like a server-side JS framework.

Here is a way I just came up with, but I admit it is very clumsy.

Array(2 + 1).join("Hello-").split("-").join('');

see comment :P

braks
  • 1,267
  • 11
  • 21
0

You can replace the word starting with a upper case letter with itself 2 times like

"HelloHello".replace(/([A-Z][^A-Z]*)/, '$1$1')
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0

String.prototype.replace() allows for a function to be passed to do the replacement, which you can use like:

var a = '123',
    words = ['foo', 'bar', 'baz'];

a = a.replace(/\d/g, function (match, i){
    return words[i].repeat(match);
});

Which gives:

foobarbarbazbazbaz

http://jsfiddle.net/eqz2y58h/1/

Or (more explicit):

var a = '123',
    words = ['foo', 'bar', 'baz'];

a.match(/\d/g).forEach(function (b, c){
    a = a.replace(new RegExp(b, 'g'), words[c].repeat(b));
});

Gives:

foobarbarbazbazbaz

http://jsfiddle.net/eqz2y58h/

Jared Farrish
  • 46,034
  • 16
  • 88
  • 98
0

Here's a function:

function repeatWord(str, n) {
    return str + Array(n + 1).join(str.match(/(.*)\1/)[1]);
}

You can use it like:

repeatWord('HelloHello', 3);

'HelloHelloHelloHelloHello'

The 3 means to add Hello to the end 3 more times.


In ES6 Harmony, there is a repeat function. You can add this:
String.prototype.repeat||String.prototype.repeat = a => {
    var b =  '', _i = 0;
    for (; _i < +a; _i += 1)  b += this;
    return b;
};

You can use it like:

"Hello".repeat(3);

"HelloHelloHello"


Also this might be what you want:

function repeat (format, n) {
    return Array(+n + 1).join(format);
}

repeat('Hello', '3');

'HelloHelloHello'

Downgoat
  • 11,422
  • 5
  • 37
  • 64