HarshWombat HarshWombat - 1 year ago 63
HTML Question

How do I replace all spaces, commas and periods in a variable using javascript

I have tried

var res = str.replace(/ |,|.|/g, "");
var res = str.replace(/ |,|.|/gi, "");
. What am I missing here?

var str = "Text with comma, space, and period.";
var res = str.replace(/ |,|.|/g, "");

Answer Source

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 [...].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download