最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How do I replace all spaces, commas and periods in a variable using javascript - Stack Overflow

programmeradmin4浏览0评论

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);

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);

Share Improve this question edited Sep 30, 2016 at 16:44 HarshWombat asked Sep 6, 2016 at 9:37 HarshWombatHarshWombat 1692 gold badges2 silver badges9 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 17

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, "")

You can use these lines:

str = str.replace(/[ ,.]/g,'');

Plus i have added a fiddle for this at Fiddle

发布评论

评论列表(0)

  1. 暂无评论