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 [].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With