简体   繁体   English

无法在 Javascript 中替换字符串中的“[”和“]”字符

[英]Can't replace “[” and “]” characters in a string in Javascript

I'm trying to replace "[" and "]" characters in the string using javascript.我正在尝试使用 javascript 替换字符串中的“[”和“]”字符。

when I'm doing当我在做

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

then it works fine - but the problem is I have a lot of this characters in my string and I need to replace all of the occurrences.然后它工作正常 - 但问题是我的字符串中有很多这样的字符,我需要替换所有出现的字符。

But when I'm doing:但是当我这样做时:

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

or或者

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

nothing is happens.什么都没有发生。 I've also tried with HTML numbers like我也尝试过使用 HTML 数字,例如

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

but it doesn't work neither.但它也不起作用。 Any ideas how to make it?任何想法如何制作?

You either need to escape the opening square bracket, and add a pipe between them:您要么需要转义方括号,并在它们之间添加一个管道:

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

Or you need to add them in a character class (square brackets) and escape them both:或者您需要将它们添加到字符类(方括号)中并将它们都转义:

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." ...有12个字符具有特殊含义:反斜杠\\ ,插入符号^ ,美元符号$ ,期间或点缀. ,竖线或管道符号| ,问号? ,星号或星* ,加号+ ,左括号( ,右括号)和左方括号[ ,左花括号{ ... 如果您想在正则表达式中使用这些字符中的任何一个作为文字,您需要转义他们用反斜杠。”

[] in a regex is a character class. []在正则表达式中是一个字符类。 Since you haven't escaped, them you're saying a "find any of the following characters", and not providing any.由于您没有逃脱,他们说“找到以下任何字符”,而不是提供任何字符。 Try /[\\[\\]]/ instead.尝试/[\\[\\]]/代替。

edit: @andy is right.编辑:@andy 是对的。 forgot to put in a container [] .忘记放入容器[]

这是一个简单的解决方案:

newString = oldString.split("[]").join("");

had a similair situation.有类似的情况。 i just used backslash like so.我只是像这样使用反斜杠。

-replace '\[','' -replace ']',''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM