Cannot replace characters "[" and "]" in a string in Javascript

I am trying to replace the characters "[" and "]" in a string using javascript.

when i do

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

then it works fine, but the problem is that I have a lot of these characters in my string and I need to replace all occurrences.

But when I do:

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

or

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

Nothing happens. I also tried with HTML numbers like

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

but it does not work. Any ideas how to do this?

+4
source share
4 answers

You either need to avoid the square opening bracket, and add a pipe between them:

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

Or you need to add them to a character class (square brackets) and avoid both of them:

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

Demo

"... 12 : \, ^, $, ., |, ?, *, +, (, ) [, {... , ".

+10

[] . , " " . /[\[\]]/.

edit: @andy . [].

+7

This is a simple solution:

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

I want to replace the character "}", but I can’t. enter image description here

or I use the replacement (/} /, "-"), but it doesn’t work either

0
source

All Articles