如何使用javascript替换变量中的所有空格,逗号和句点

时间:2022-02-04 16:49:44

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

我试过var res = str.replace(/ |,|。| / g,“”);和var res = str.replace(/ |,|。| / gi,“”);。我在这里想念的是什么?

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

3 个解决方案

#1


5  

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

你也可以使用|运算符,但在这种情况下,您必须转义句点,因为普通句点将与任何字符匹配。作为一般性评论,如果在正则表达式中,您有多个备选方案所有都由一个字符组成,最好使用带有[...]的集合。

#2


2  

You need to escape dot \.:

你需要逃脱点\:

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

#3


1  

You can use these lines:

你可以使用这些行:

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

Plus i have added a fiddle for this at Fiddle

另外,我在Fiddle添加了一个小提琴

#1


5  

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

你也可以使用|运算符,但在这种情况下,您必须转义句点,因为普通句点将与任何字符匹配。作为一般性评论,如果在正则表达式中,您有多个备选方案所有都由一个字符组成,最好使用带有[...]的集合。

#2


2  

You need to escape dot \.:

你需要逃脱点\:

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

#3


1  

You can use these lines:

你可以使用这些行:

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

Plus i have added a fiddle for this at Fiddle

另外,我在Fiddle添加了一个小提琴