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

Let's say I have a line:

"__3_" 

... which I would like to refer to:

 "__###_" 

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

I understand that backlinks can be used with str.replace()

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

And we can use str.repeat(n) to repeat sequences of strings n times.

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

 str.replace(/([0-9])/g,"#".repeat("$1")) 
+7
javascript regex
source share
4 answers
 "__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 to replace __11+ with "#".repeat(11) - change regexp to /\d+/

Is this what you want?

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

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

and if you use the function as the second parameter

function (replacement) The function called to create a new substring (instead of the "substring" obtained from parameter No. 1). The arguments provided to this function> are described below in the section "Specifying a function as a parameter".

+7
source share

Try the following:

 var str = "__3_"; str = str.replace(/[0-9]+/, function(x) { return '#'.repeat(x); }); alert(str); 
+5
source share

Old fashioned approach:

 "__3__".replace(/\d/, function (x) { return Array(+x + 1).join('#'); }); 
+2
source share

Try the following:

 var str = "__3_"; str = str.replace(/[0-9]/g,function(a){ var characterToReplace= '#'; return characterToReplace.repeat(a) }); 
0
source share

All Articles