Is there a way using JavaScript's RegEx engine to convert
"2"
-> "HelloHello"
?
"3"
-> "HelloHelloHello"
?
Is there a way using JavaScript's RegEx engine to convert
"2"
-> "HelloHello"
?
"3"
-> "HelloHelloHello"
?
"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
You can replace the word starting with a upper case letter with itself 2 times like
"HelloHello".replace(/([A-Z][^A-Z]*)/, '$1$1')
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
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.
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'