我试图格式化我的值只接受数字并用点替换逗号,但我不能用点替换逗号。
示例:
"4,82 €".replace(/[^\d\,]/g, '')
成功价值: 4.82
答案 0 :(得分:0)
试试这个:'4,82 €'.replace(/[^0-9,]/g, '').replace(/,/g, '.');
此外,您不需要逃离,
。它在regex
答案 1 :(得分:0)
尝试通过两个单独的表达式处理此问题,一个用于删除,另一个用于执行替换:
这可能类似于下面的表达式:
// Replaces all non-digits and commas /[^\d,]/ and replaces commas /,/
input.replace(/[^\d,]/g, '').replace(/,/g,'.`');
示例强>
// Replace any non-digit or commas and then replace commas with periods
console.log("4,82 € -> " + "4,82 €".replace(/[^\d\,]/g, '').replace(/,/g,'.'))
// If you want to allow periods initially, then don't remove them
console.log("4.82 € -> " + "4.82 €".replace(/[^\d\,.]/g, '').replace(/,/g,'.'))
答案 2 :(得分:0)
你几乎是对的,只是错过了一件小事。
你的正则表达式
[^ \ d \,]
只会替换一个非数字或逗号字符,而不是全部。
将正则表达式更改为
像这样[^ \ d \,] +
" 4,82€" .replace(/ [^ \ d \,] + / g,'')
它会起作用