Javascript search and replace sequence of characters that contain square brackets

隐身守侯 提交于 2019-12-22 13:47:19

问题


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, ''));

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

Any advice would be much appreciated


回答1:


If you just want to replace a single instance of it you can just str = str.replace("[EN] ", ""); otherwise; var find = "\\[EN\\]";.




回答2:


Try setting your regex this way:

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



来源:https://stackoverflow.com/questions/2713702/javascript-search-and-replace-sequence-of-characters-that-contain-square-bracket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!