Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
user2654186 Avatar asked May 28 '15 14:05

user2654186


2 Answers

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

like image 132
Andy Avatar answered Nov 15 '22 06:11

Andy


[] 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 [].

like image 43
Marc B Avatar answered Nov 15 '22 04:11

Marc B