1

Hey guys I'm trying to remove two characters and any white space from a string that looks like this.

var num1 = "34 345 324.34 $"
var num2 = "$34,345,324.34"

I basically want to remove $ and , and white space

so far I have this

num1.replace(/,|\s/g,""); //34345324.34$
num2.replace(/,|\s/g,""); //$34345324.34

How do I also delete the $

Thank you.

3
  • replace(/[$,\s]/g,"") Commented May 30, 2017 at 19:43
  • .replace(/[$,\s]+/g, ""); Commented May 30, 2017 at 19:44
  • Wouldn't it be more robust to just keep numerals and decimal points? E.g. num2.replace(/[^\d.]/g, '') Commented May 30, 2017 at 19:45

3 Answers 3

1

You seem to be dealing with currency strings. You may follow your blacklist approach and use .replace(/[,\s$]+/g,"") to remove all occurrences of 1+ commas, whitespaces and dollar symbols. However, once you have a pound, euro, yen, etc. currency symbol, you will have to update the regex.

Using a whitelisting approach is easier, remove all chars that are not on your whitelist, digits and dots:

.replace(/[^0-9.]+/g,"")

See the regex demo.

The [^0-9.]+ matches 1 or more occurrences of any chars other than (the [^...] is a negated character class that matches the inverse character ranges/sets) digits and a dot.

JS demo:

var nums = ["34 345 324.34 $",  "$34,345,324.34"];
var rx = /[^0-9.]+/g;
for (var s of nums) {
  console.log(s, "=>", s.replace(rx, ""));
}

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

Comments

1

For white space in the beginning of the string (or the end) use str.trim();, it will strip any trailing whitespaces from the beginning and/or the end of the string that contains them.

Comments

0

To remove all dots, spaces and dollars, add the dollar sign (escaped) into your regex:

/,|\s|\$/g

or simply

/[,\s\$]/g

Demo:

var num1 = "34 345 324.34 $"
var num2 = "$34,345,324.34"

var res1 = num1.replace(/[,\s\$]/g,""); //34345324.34
var res2 = num2.replace(/[,\s\$]/g,""); //34345324.34

console.log(res1)
console.log(res2)

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.