I have tried var res = str.replace(/ |,|.|/g, "");
and var res = str.replace(/ |,|.|/gi, "");
. What am I missing here?
var str = "Text with comma, space, and period.";
var res = str.replace(/ |,|.|/g, "");
document.write(res);
If you just want to delete all spaces, commas and periods you can do it like that:
var res = str.replace(/[ ,.]/g, "");
You can also use the |
operator, but in that case you have to escape the period, because a plain period will match with any character. As a general remark, if in a regular expression you have multiple alternatives with |
that all consist of a single character, it is preferable to use a set with [...]
.
You need to escape dot \.
:
"Text with comma, space and period.".replace(/ |,|\.|/g, "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With