Reuben L. Reuben L. - 6 months ago 29
Javascript Question

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

Let's say I have a string:

"__3_"


...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
str.replace()


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


And that we can use
str.repeat(n)
to repeat string sequences
n
times.

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

str.replace(/([0-9])/g,"#".repeat("$1"))

Answer
"__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?

According https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

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.