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.
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.
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, "")); }
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.