使用正则表达式和 javascript 进行货币字符串转换

Lui*_*ves 2 javascript regex

我有一个货币价值,"R$ 2.200,00"因为我的千.位分隔符和我的小数点分隔符是,.

我希望 um regex 将此字符串转换为有效的 MySQL 十进制数。

可能的值:

"R$ 23.000,20", "23.000,30", "R$ 1300,20", "R$ 100","161,43256"

结果将是:

"23000.20", "23000.30", "1300.20", "100","161.43256"

我的尝试如下,但它不起作用。我只想接受数字和点(。)作为结果。

const str = "R$ 2.200,000";
const res = str
  .replace(/R$/gi, "")
  .replace(/./gi, "")
  .replace(/,/gi, ".");
console.log(res);
Run Code Online (Sandbox Code Playgroud)

kor*_*hyk 7

通过优化,这似乎有效:

const possible = [
  "R$ 23.000,20",
  "23.000,30",
  "R$ 1300,20",
  "R$ 100 ",
  "161,43256",
  "R$ -23.000,20",
  "-23.000,30",
  "R$ -1300,20",
  "R$ -100",
  "-161,43256"
]
const rx = /[^\d,-]+/g      // Match everything except digits, comma and negative
const parseNumber = num =>
  num
  .replace(rx, '')          // Filter digits and comma
  .replace(',', '.')        // Replacing comma with dot

possible.forEach(num => {
  console.log(num, '\t->\t', parseNumber(num))
})
Run Code Online (Sandbox Code Playgroud)