在下面的代码中,每 3 位数字后放置一个逗号
{
var commaString = valueWthOutComma.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
是否可以在上面的 RegEx 中传递任何变量来代替“3”,我想要的是
{
var comma_place = 2 ; //any value can be place
var commaString = valueWthOutComma.replace(/\B(?=(\d{comma_place})+(?!\d))/g, ",");
}
最佳答案
要执行您需要的操作,您需要将正则表达式构建为字符串而不是文字,并将其提供给 RegExp()
构造函数,如下所示:
var comma_place = 2; //any value can be place
var re = new RegExp('\B(?=(\d{' + comma_place + '})+(?!\d))', 'g');
// var re = new RegExp(`\B(?=(\d{${comma_place}})+(?!\d))`, 'g'); // ES6 - won't work in IE
var commaString = valueWthOutComma.replace(re, ",");
关于javascript - 是否可以在替换方法中传递变量而不是常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139435/