Skip to content Skip to sidebar Skip to footer

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

Solution 1:

"__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.

Solution 2:

Try this:

var str = "__3_";

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

alert(str);

Solution 3:

Try this:

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

Post a Comment for "Replacing An Integer (n) With A Character Repeated N Times"