JVG
JVG

Reputation: 21150

Javascript regex to remove anything but numbers from the start of a string

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

Upvotes: 2

Views: 1069

Answers (2)

Anirudha
Anirudha

Reputation: 32797

You can do this

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

Upvotes: 2

akonsu
akonsu

Reputation: 29536

maybe

string.replace(/^[^0-9]*/, "");

Upvotes: 4

Related Questions