Reuben L. Reuben L. - 4 months ago 21x
Javascript Question

Replacing an integer (n) with a character repeated n times

Let's say I have a string:


...which I would like to turn into:


basically replacing an integer with repeated occurrences of
equivalent to the integer value. How can I achieve this?

I understand that backreferences can be used with

var str = '__3_'
str.replace(/[0-9]/g, 'x$1x'))
> '__x3x_'

And that we can use
to repeat string sequences

But how can I use the backreference from
as the argument of
? For example, this does not work:


"__3_".replace(/\d/, function(match){ return "#".repeat(+match);})

if you use babel or other es6 tool it will be

"__3_".replace(/\d/, match => "#".repeat(+match))

if you need replace __11+ with "#".repeat(11) - change regexp into /\d+/

is it what you want?


str.replace(regexp|substr, newSubStr|function)

and if you use function as second param

function (replacement) A function to be invoked to create the new substring (to put in place of the >substring received from parameter #1). The arguments supplied to this function >are described in the "Specifying a function as a parameter" section below.