2

I have some strings like this:

var st1 = 'AU$99.95'; // Should return 99.95

var st2 = 'AU.99.95'; // Should return 99.95

var st1 = 'Blahblah $99,000'; // Should return 99,000

My current regex gets me most of the way there, I'm just using string.replace(/[^0-9.,]/g, "");.

This works for all scenarios except for #2, when there is an allowed character that is before a number. I want to ONLY allow . and , when there is a number preceding it. How can I achieve this?

(I know I can write a javascript function to do this, but I'd rather take care of it all in the one regex replace)

EDIT:

Apologies, small oversight. I also need to remove any text after the number (I assumed before/after numbers wouldn't make a difference, but apparently they do!). So:

var st4 = 'blahblah $.99,000AUD // should return 99,000

2
  • what about $99.99 only Commented Jul 23, 2013 at 14:53
  • @Anirudh Great point. If you make an answer with this updated query I'll mark it as correct. Commented Jul 24, 2013 at 0:11

2 Answers 2

4

maybe

string.replace(/^[^0-9]*/, "");
Sign up to request clarification or add additional context in comments.

1 Comment

This matches the empty prefix and forces a replacement even when the first character is a digit. Use /^[^0-9]+/ to prevent this.
2

You can do this

str.replace(/^[^\d]*/,"").replace(/[^\d]*$/,"");

Comments

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.