我的货币值为"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);
最佳答案
经过优化,这似乎可以正常工作:
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))
})
关于javascript - 将正则表达式与javascript一起使用以进行货币字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62615575/