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

编程入门 行业动态 更新时间:2024-10-28 08:26:28
本文介绍了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 - 正则表达式
  • 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

本文发布于:2023-11-29 23:46:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648000.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   javascript   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!