正则表达式和替换字符串

时间:2016-07-08 14:22:00

标签: javascript regex

我试图格式化我的值只接受数字并用点替换逗号,但我不能用点替换逗号。

示例:

"4,82 €".replace(/[^\d\,]/g, '')

成功价值: 4.82

3 个答案:

答案 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,'')

它会起作用