javascript - 无法用 Javascript 替换字符串中的 "["和 "]"字符

标签 javascript regex

我正在尝试使用 javascript 替换字符串中的“[”和“]”字符。

当我在做的时候

newString = oldString.replace("[]", "");

然后它工作正常 - 但问题是我的字符串中有很多这样的字符,我需要替换所有出现的字符。

但是当我在做的时候:

newString = oldString.replace(/[]/g, "");

newString = oldString.replace(/([])/g, "");

什么都没有发生。我也试过像

这样的 HTML 数字
newString = oldString.replace(/[]/g, "");

但它也不起作用。有什么制作方法吗?

最佳答案

您要么需要转义左方括号,然后在它们之间添加管道:

newString = oldString.replace(/\[|]/g, "");

或者您需要将它们添加到字符类(方括号)中并将它们都转义:

newString = oldString.replace(/[\[\]]/g, "");

DEMO

"...there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {... If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash."

关于javascript - 无法用 Javascript 替换字符串中的 "["和 "]"字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30509672/

相关文章:

javascript - 在我的网页上尝试编辑器

javascript - IE8 触发更改事件的问题

vb.net - 时间 24 小时格式的 .NET 正则表达式

regex - Scala 按包含所有连字符的行拆分多行字符串

javascript - 如何用jquery控制html属性

Javascript - FileReader 如何一次读取和处理多个文件中的每个文件

JavaScript如何在Promise onSuccess之外获取在Promise内部分配的变量值

javascript - Firefox 上的正则表达式问题

java - java中整数的正则表达式

regex - 检查字符串与所有给定的正则表达式集之间是否存在匹配