-1

I need help splitting string in javascript.

I have a string with currency. The string depends on the location.

For example: "1,99€" or "$1,99"

I would like to split the string and extract the "amount" and the "currency" out of it.

If this fails, I would like to return an empty string or just null.

Does someone know how to solve that?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Fargho
  • 1,267
  • 4
  • 15
  • 30

5 Answers5

4

You can try to match and replace using regex

var extractMoney = function(string) {
  var amount = string.match(/[0-9]+([,.][0-9]+)?/)
  var unit = string.replace(/[0-9]+([,.][0-9]+)?/, "")
  if (amount && unit) {
    return {
      amount: +amount[0].replace(",", "."),
      currency: unit
    }
  }
  return null;
}

console.log(extractMoney("1,99€"));
console.log(extractMoney("$1,99")); 
console.log(extractMoney("error"));

results

extractMoney("1,99€"); // => {amount: 1.99, currency: "€"}
extractMoney("$1,99"); // => {amount: 1.99, currency: "$"}
extractMoney("error"); // => null
mleko
  • 11,650
  • 6
  • 50
  • 71
2

If you expect all inputs to include both decimals of the cent value (ie, your comma will always be followed by 2 digits) you could use this:

const amount = money.match(/\d/g).join('') / 100;
const curren = money.match(/[^\d,]/g).join('');

JavaScripts much hated implicit type coercion allows us to divide that string numerator by a number denominator and end up with a number.

To get the currency, we simply extract all non- digit or comma characters and join them.

If you can't rely on the input including the cent value (ie, you might receive a whole dollar amount without a comma or cent digits) try this:

const amount = money.match(/d/g).join('') / (money.includes(',') ? 100 : 1);
wbadart
  • 2,583
  • 1
  • 13
  • 27
2

Try this way to get amount and currency symbol from the string with currency

var price = '1,99€';
//var price = '$1,99';
var amount = Number( price.replace(/[^0-9\.]+/g,""));
var currency = price.match(/[^\d,]/g).join('');
console.log(amount);
console.log(currency);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

I think the best way would be to use regular expressions, there's a post here: How to convert a currency string to a double with jQuery or Javascript? that should cover your needs:

var currency = "GB$13,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));

but different cultures write the decimal points in different ways, some use commas, some use full stop, so you might need to tweak the expression if you have to handle these cases.

Myke Black
  • 1,299
  • 15
  • 15
0

For a comprehensive solution I would look into leveraging an existing library like money.js:

http://openexchangerates.github.io/money.js/

This would be more appropriate for a real world product, but I'm not sure if you are doing this as a learning exercise or something else.

John McMahon
  • 1,605
  • 1
  • 16
  • 21