从字符串价格中获取货币符号

Dro*_*nax 0 javascript

我有价格:

var str1 = '10,00 €';
var str2 = '12.22 $';
Run Code Online (Sandbox Code Playgroud)

我只需要获取货币符号。我写的功能:

 function stringToCurrency(str){
    return Number(str.replace("€", "").replace("$", "");
}
Run Code Online (Sandbox Code Playgroud)

但这只能替换上的货币符号''。我如何获得货币符号?

CBa*_*arr 5

如果我们使用正则表达式删除所有其他内容(数字,句点,逗号,空格),那么我们只剩下货币符号

var str1 = '10,00 €';
var str2 = '12.22 $';

function getCurrencySymbol(str) {
  //replace all numbers, spaces, commas, and periods with an empty string
  //we should only be left with the currency symbols
  return str.replace(/[\d\., ]/g, '');
}

console.log(getCurrencySymbol(str1));
console.log(getCurrencySymbol(str2));
Run Code Online (Sandbox Code Playgroud)

  • 可以,但是逗号,句点,空格也是非数字的,这些也将被返回 (2认同)