简体   繁体   中英

Convert dollar to any currency

I am still a newbie in regular expression, please help me out guys.

I have this html file, some of the paragraphs contains dollar values ($200, $300 etc). Whenever a user visits that file it will convert those values into their own currency.

I want to use regular expression to look for those values and have proper conversion.

Thanks in advance!

Here is a working example with few assumptions. I believe you have the conversion factor and you can substitute the actual value with the conversion factor.

Edit: modified to allow conversion only for the matching numerical values. Numerical values are assumed to be positive integer values.

Fiddle here http://jsfiddle.net/gbsandeep/eBQFE/

Example:

  • Converted from currency "$" to hypothetical currency with symbol "@"

  • Conversion factor: 0.05

Input

$200 some $100 content goes $300 here

Output

@10 some @5 content goes @15 here

 function convert() {
     var replacedText = document.getElementById('myPara').innerText;
     var newCurrencySymbol = '@';
     var currencyConversionFactor = 0.05;
     var numberPattern = /\$\d+/g;
     var numbers = replacedText.match(numberPattern);
     for (var i = 0; i < numbers.length; i++) {
         // extract numerical value
         var num = numbers[i].match(/\d+/);
         // your currency conversion here
         var newNum = newCurrencySymbol + (num * currencyConversionFactor);
         replacedText = replacedText.replace(numbers[i], newNum);
     }
     document.getElementById('convertedPara').innerText = replacedText;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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