[英]regex - detect and replace more then two digits in string
As soon as there are more then two digits in a string, I want to replace only them the digits. 字符串中一旦有两个以上的数字,我只想替换它们。 Example:
例:
allowed: 允许:
bla 22 bla bla
should be replaced: 应该更换:
bla 234 bla 8493020348 bla
to 至
bla *** bla ********** bla
The exact numbers don't matter - just 1-2 digits should be displayed and if there are more then 2, then they should be replaced. 确切的数字无关紧要-仅显示1-2位数字,如果显示的数字多于2位,则应将其替换。
This is what I've already tried, but it always replaces the whole string and not only the digits....further if 2 digits are accepted and later on there's a third digit it gets triggered as well.. 这是我已经尝试过的方法,但是它总是替换整个字符串,而不仅是数字。...此外,如果接受2位数字,后来又有第三位数字被触发。
var regex = /^(?:\D*\d){3}/g;
str = str.replace(regex, "**");
So this won't work: 所以这行不通:
bla 12 and so on 123
It will become: 它将变为:
**
But I want it to be like this: 但我希望它是这样的:
bla 12 and so on ***
Thank you SO much in advance!! 提前非常感谢您!!
One solution is to pass a callback function to String.prototype.replace()
and use String.prototype.repeat()
to put in the correct number of asterisks: 一种解决方案是将回调函数传递给
String.prototype.replace()
并使用String.prototype.repeat()
放入正确数量的星号:
string = string.replace(/\d{3,}/g, (v) => '*'.repeat(v.length));
Complete snippet: 完整代码段:
const string = 'bla 22 bla 234 bla 8493020348 bla'; const result = string.replace(/\\d{3,}/g, (v) => '*'.repeat(v.length)); console.log(result); // "bla 22 bla *** bla ********** bla"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.