Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 689
HarshWombat Avatar asked Sep 06 '16 09:09

HarshWombat


2 Answers

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

like image 156
redneb Avatar answered Oct 31 '22 01:10

redneb


You need to escape dot \.:

"Text with comma, space and period.".replace(/ |,|\.|/g, "")
like image 39
madox2 Avatar answered Oct 30 '22 23:10

madox2