In my VF page I have some Javascript to format passed variables. I have a string eg "Cost is $100.00" from which I need to remove all non-digit characters, EXCEPT the digital period. I want the result to be 100.00

I currently have:

var x = "Cost is $100.00";
var y = x.replace(/\D/g, '');

which removes all non-digit characters, including the "." What do I need to do to keep that?


You can write a negated character class with ^ to include the period, ., and the set of digits, 0-9:

var z = x.replace(/[^0-9.]/g, '');

z is then "100.00".

| improve this answer | |
  • Seeing a proposed edit prompted me to add this comment. Normally, a period/full-stop is a wildcard (matches any single character), and you'd need to escape it to match a literal "period". However, since it appears in a character class, it does not need to be escaped. – Derek F Apr 22 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.