我正在尝试使用 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, "");
"...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/