简体   繁体   中英

JavaScript Function to Regex Find Prices and Detect Currency

I would like to create a JavaScript function that uses Regex to find prices from an input string and detects the currency of the price.

The format I'm going for is:

function handleCurrency (string) {  
    // ...
    return {price: ..., type: ...} 
}

For example, if the input string is, "test $105.62 (29,867.80 bits) (29,897.90 bits) (29,827.14 bits) test", the returned object would be:

{price: 105.62, type: '$'}

To start, the function should support euros, dollars, and pounds. It would also need to support the following currency formats:

  • $100.00
  • (28,278.54 bits) (28,307.04 bits) $ 100.00
  • $100.00 (28,278.54 bits) (28,307.04 bits) USD
  • $ 100.00 USD
  • 100.00 USD
  • 100.00 $
  • etc.

All of these would be detected as:

{price: 100, type: 'USD'}

Thanks in advance!

Edit: I wrote function that solves my question. Thanks for all the help!

function handleCurrency (string) {
    let filter = input
    filter = filter.replace(/USD/g,'$')
    filter = filter.replace(/EUR/g,'€')
    filter = filter.replace(/GBD/g,'£')
    filter = filter.replace(/(?<!\d)\.(?!\d)/g, '')
    filter = filter.replace(/[^\$\€\£\d\.]/g,'')

    let price = filter
    price = price.replace(/[^\d\.]/g,'')
    price *= 1

    let type = filter
    type = type.replace(/[^\$\€\£]/g,'')
    type = type[0]

    return {price: price, type: type}
}

Stack Overflow isn't here to write code for you. Stack Overflow is here, if you're stuck on a problem and need help. As an example, try to write such an regex, state on which cases it works and on which it doesn't. If that doesn't help you to figure it out, ask a question.

As a resource to get started I'd point you at https://regex101.com/ which does an awesome job at explaining what exactly your regex is matching and where you can experiment with different inputs. You can also save your regex including the input and then attach it to a question here if you get stuck.

Since you're new, I've made a quick example, which catches all given examples: https://regex101.com/r/cP5f94/1 you still need to build a Javascript object with them and map $ to USD , add additional cases, ect. but it should get you started

Good Luck!

Please First try to solve the problem and if you still can't solve it ask. Hope this helps. Use https://regexr.com/ to make your regular expressions and codepen to test your code.

function findCurrency (string) {  
    let text = string.match('(\$)? ?([0-9.]+)(?: ?(USD))?');
  let curr;
  if(text[0]=='$' || text[2]=='USD')
    curr = 'USD'
  return {price: text[1], currencyType: ...} 
}

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