javascript删除字符串中出现的所有char [英] javascript delete all occurrences of a char in a string

查看:74
本文介绍了javascript删除字符串中出现的所有char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除所有字符,例如 [] &
[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 - Regular Expressions
  • http://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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆