0

I need to parse some data that contains comma formatted numbers and text like this, keeping only numerical part:

"The stock is 1,124 units"

I came up with this regex that is working great, except for numbers under 0, example a price that could be 0,259 EUR

qty = qty.textContent.replace(/\D/g,'');

How can I modify for removing only text, but still keeping the sense of original number

I'd like -> 0.259 Not -> 0259

EDITED

I need both situations, thousands separator and decimal place.

Depending on parse, could be USD when comma is thousands separator, or EUR, where dot is decimal place. I will make a switch case for currency and thank you for your fast answers!

2
  • Ok, so that comma is a thousands separator and not a decimal separator, right? Is there any other punctuation in the original string? Commented May 31, 2017 at 20:15
  • see edited, thank you Commented May 31, 2017 at 20:21

2 Answers 2

2

So long as there are no periods in the string overwise, then this should work:

qty = qty.textContent.replace(/[^\d\.]/g,'');

If there is (or might be) other periods, then it gets a little more tricky.

You might try something like:

([^\d.]|\.(?!\d))

This will match characters that aren't numeric digits or periods, or periods that aren't followed by another digit. So something like this should work:

"The st.oc.k is 1,124.22 units.".replace(/([^\d.]|\.(?!\d))/g,"")

Gives you back: 1124.22

Sign up to request clarification or add additional context in comments.

1 Comment

I accepted yours because it's working, however, I use /[^\d\.,]/g then replace comma if USD. Thank you Matt!
2

This regex should work

\d+(\,|\.)\d+

It matches both 1,230 and 0.123

If you want to remove the comma you can do this

yourstr.replace(",", "");

2 Comments

I believe the original intent was to remove the comma. Although the question isn't exactly clear, but that's what the OP's original does.
I need both, sorry for confusion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.