0

Based off a simlar question asked here - How to convert a currency string to a double with jQuery or Javascript?, I need to take a currency that can be in the format of

-143,000.00 and convert it for 2 scenarios:

  1. Where the output would be -143000.00
  2. Where the output would be -1430000

I am not good at all with regular expressions so I have tried some hack such as these 2 below:

  1. I need to remove all of the currency except for the -
const value = "-143,000.00";
Number(value.replace(/[^0-9.,]+/g, ''))

and my second use case is I need to remove all but keep the - and the .

const value = "-143,000.00";
Number(value.replace(/[^0-9.-]+/g, ''));

Thank you for assistance that you can give.

pertrai1
  • 4,146
  • 11
  • 46
  • 71
  • What is your problem? What you couldn't to do? – slesh May 23 '20 at 21:57
  • In your number `2` one zero is less than the result. is that correct? – Alireza HI May 23 '20 at 21:57
  • Consider using a library like currency.js if you have to do more than those two things. If it's only those two, I'm not entirely sure what your problem is. I think `Number(value.replace(/[^0-9.\-]+/g, ''))` and `Number(value.replace(/[^0-9\-]+/g, ''))` would solve 1 and 2 respectively but I don't really get it – paolostyle May 23 '20 at 22:02
  • I have updated the question. These are the only 2 scenarios that I have and I am using 2 variables to store the replacements in. The second I have updated where I need to remove the `,` but keep the `-` and the `.`. That is the one that is not working for me with my regular expression. – pertrai1 May 23 '20 at 22:10

1 Answers1

1

Is this what you are looking for?

const value = "-143,000.00";

var n1 = value.replace(/([^\d.+-]+)/g,"");
var n2 = Number(n1);

console.log("n1 : ",n1)   // "-143000.00"
console.log("n2 : ",n2)   // -143000
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42