简体   繁体   English

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

[英]Get currency symbol from a string price

I have a prices: 我有一个价格:

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

I need get only currency symbol. 我只需要获取货币符号。 I writed function: 我写的功能:

 function stringToCurrency(str){
    return Number(str.replace("€", "").replace("$", "");
}

But this only replace currency symbol on '' . 但这只会替换''''货币符号。 How I can get currency symbol? 我如何获得货币符号?

If we use a regex to remove everything else (numbers, periods, commas, spaces) then we are only left with the currency symbols 如果我们使用正则表达式删除所有其他内容(数字,句点,逗号,空格),那么我们只剩下货币符号

 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)); 

Just pick the last char of the string 只需选择字符串的最后一个字符

function stringToCurrency(str) {
    return str.trim().charAt(str.length - 1);
}

You can simply write a function that returns the last character of the string which represents the symbol that you want. 您可以简单地编写一个函数,该函数返回代表所需符号的字符串的最后一个字符。 Since Javascript string is a char array, you can access the last character by the length of the string as follows. 由于Javascript字符串是一个char数组,因此您可以按如下所示按字符串的长度访问最后一个字符。

function stringToCurrency(str){
    return str[str.length-1];
}

Hope It will help you! 希望对您有帮助! Thanks 谢谢

The way Number() works, is it returns an integer given any set of data. Number()工作方式是在给定任何数据集的情况下返回整数。 When you're passing these variables into it, like '10,00 €' , the Number function will return NaN because you're passing symbols and spaces into it. 当您将这些变量传递给它时,例如'10,00 €'Number函数将返回NaN,因为您正在向其中传递符号和空格。

To return only the symbol, JS has built-in methods that can be chained on to easily deal with this. 为了只返回符号,JS具有内置的方法,可以将其链接起来以轻松地处理它。

If the location is known, but value not, we can return the value of the given string location with charAt() 如果位置已知,但值未知,则可以使用charAt()返回给定字符串位置的值

function knownLocation(s) {
  return s.charAt(s.length -1)
}

If the location of that symbol is unknown , but you know it's there, we can check which is there with .includes and then return the character at the index. 如果该符号的位置未知 ,但您知道它在此处,则可以使用.includes检查其中在哪,然后在索引处返回该字符。

function knownValue(s) {
 if (s.includes("$")) {
    return s.charAt(s.indexOf("$"))
 } else if (s.includes("€")) {
   return s.charAt(s.indexOf("€"))
 } else {
   return undefined
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM