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

不羁的心 提交于 2021-01-21 04:25:30

问题


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"))

回答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.




回答2:


Try this:

var str = "__3_";

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

alert(str);



回答3:


Old fashioned approach:

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



回答4:


Try this:

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


来源:https://stackoverflow.com/questions/37507205/replacing-an-integer-n-with-a-character-repeated-n-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!