在下面的代码中,逗号每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, ",");
}
答案 0 :(得分:3)
要执行所需的操作,您需要将正则表达式构建为字符串而不是文字,并将其提供给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, ",");