Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"))
like image 927
Reuben L. Avatar asked May 29 '16 07:05

Reuben L.


2 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 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.

like image 60
Vasiliy Vanchuk Avatar answered Oct 19 '22 15:10

Vasiliy Vanchuk


Try this:

var str = "__3_";

str = str.replace(/[0-9]+/, function(x) {
      
  return '#'.repeat(x);
});

alert(str);
like image 6
Ali Mamedov Avatar answered Oct 19 '22 16:10

Ali Mamedov