我想删除所有字符,例如 [或] 或& :[foo]& bar - >foo bar
I want to delete all characters like [ or ] or & in a string i.E. : "[foo] & bar" -> "foo bar"
我不想调用替换3次,是否有更简单的方法而不仅仅是编码:
I don't want to call replace 3 times, is there an easier way than just coding:
var s =[foo]& bar;
s = s.replace('[','');
s = s.replace(']','');
s = s.replace('&','');
推荐答案常规表达 [xkcd] (我感觉像他;)):
Regular expressions [xkcd] (I feel like him ;)):
s = s.replace(/[\[\]&]+/g, '');参考:
- MDN - string.replace
- MDN - 正则表达式
- www.regular-expressions.info/
- MDN - string.replace
- MDN - Regular Expressions
- www.regular-expressions.info/
旁注:
JavaScript的替换函数仅替换字符的第一次出现。因此,即使您的代码也不会替换所有字符,只替换每个字符中的第一个字符。如果要替换所有出现次数,则必须使用带有 g lobal修饰符的正则表达式 。
JavaScript's replace function only replaces the first occurrence of a character. So even your code would not have replaced all the characters, only the first one of each. If you want to replace all occurrences, you have to use a regular expression with the global modifier.
更多推荐
javascript删除字符串中出现的所有char
发布评论