6

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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

so clean this is the best answer
2

You need to escape dot \.:

"Text with comma, space and period.".replace(/ |,|\.|/g, "") 

Comments

1

You can use these lines:

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

Plus i have added a fiddle for this at Fiddle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.