Javascript javascript删除字符串中所有出现的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6967073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:00:58  来源:igfitidea点击:

javascript delete all occurrences of a char in a string

javascriptstring

提问by Sonnenhut

I want to delete all characters like [or ]or &in a string i.E. : "[foo] & bar" -> "foo bar"

我想删除字符串 iE 中的所有字符,如[]&:“[foo] & bar”->“foo bar”

I don't want to call replace 3 times, is there an easier way than just coding:

我不想调用替换 3 次,是否有比编码更简单的方法:

var s="[foo] & bar";

var s="[foo] & bar";

s=s.replace('[','');

s=s.replace('[','');

s=s.replace(']','');

s=s.replace(']','');

s=s.replace('&','');

s=s.replace('&','');

回答by Felix Kling

Regular expressions [xkcd](I feel like him ;)):

正则表达式[xkcd](我觉得他很像;)):

s = s.replace(/[\[\]&]+/g, '');

Reference:

参考:

Side note:

旁注

JavaScript's replacefunction only replaces the first occurrenceof 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 expressionwith the global modifier.

JavaScript 的replace函数只替换第一次出现的字符。因此,即使您的代码也不会替换所有字符,只会替换每个字符中的第一个。如果要替换所有出现的内容,则必须使用带有lobal 修饰符正则表达式g