简体   繁体   中英

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

I'm trying to replace "[" and "]" characters in the string using 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

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."

[] 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. forgot to put in a container [] .

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

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

had a similair situation. i just used backslash like so.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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