Javascript does find and replace a sequence of characters containing square brackets

I am trying to find "[EN]" in the string "Nationality [EN] [ESP]", I want to remove this from the string, so I use the replace method, code examlele below

var str = 'Nationality [EN] [ESP]';
var find = "[EN]";
var regex = new RegExp(find, "g");
alert(str.replace(regex, ''));

      

Since [EN] is identified as a character set, this will output the string "Nationality [] [ESP]", but I also want to remove the square brackets. I thought I could escape them with \, but that didn't work

Any advice would be much appreciated

+2


a source to share


2 answers


If you just want to replace one instance, you can simply str = str.replace("[EN] ", "");

otherwise; var find = "\\[EN\\]";

...



+2


a source


Try setting up your regex like this:



var regex = /\[EN\]/g;

+2


a source







All Articles