Javascript搜索并替换包含方括号的字符序列 [英] Javascript search and replace sequence of characters that contain square brackets
问题描述
我正尝试在字符串'Nationality [EN] [ESP]'中搜索'[EN]',我想从字符串中删除它,因此我使用的是替换方法,例如下面的代码>
I'm trying to search for '[EN]' in the string 'Nationality [EN] [ESP]', I want to remove this from the string so I'm using a replace method, code examaple below
var str = 'Nationality [EN] [ESP]';
var find = "[EN]";
var regex = new RegExp(find, "g");
alert(str.replace(regex, ''));
由于[EN]被标识为字符集,这将输出字符串'Nationality [] [ESP]',但我也想删除方括号.我以为我可以使用\来逃避他们,但那没用
Since [EN] is identified as a character set this will output the string 'Nationality [] [ESP]' but I want to remove the square brackets aswell. I thought that I could escape them using \ but it didn't work
任何建议将不胜感激
推荐答案
如果您只想替换单个实例,则可以 str = str.replace("[EN]",");
否则; var find ="\\ [EN \\]";
.
If you just want to replace a single instance of it you can just str = str.replace("[EN] ", "");
otherwise; var find = "\\[EN\\]";
.
这篇关于Javascript搜索并替换包含方括号的字符序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!