您可以使用下一个代码来完成这项工作:
var removeSubstring=(function(){
var fn=function($0,$1,$2,$3){return $1+$3;};
return function(str,before,after,removed){
var rg=new RegExp("("+before+")("+removed+")("+after+")","gi");
return str.replace(rg,fn);
};
})();
var str="<div class = ''></div>class class <div class ";
var before="<div ";
var after=" ";
var removed="class";
removeSubstring(str,before,after,removed);
// <div = ''></div>class class <div
但是您必须确保 inbefore
和字符串中after
的removed
内容不包含特殊的RegExp格式字符(例如.
[
]
?
*
和其他,请参阅MDN RegExp)。否则必须先转义before
,after
和removed
字符串中的这些特殊字符。
更新:
您还可以使用有效的正则表达式来before
进行after
更removed
灵活的搜索。例如下一个代码删除字母'X','V'和'Z'但不删除'x','v'和'z':
var str="qXd ezrwsvrVa etxceZd";
var before="q|w|e|r";
var after="a|s|d|f";
var removed="z|x|c|v";
removeSubstring(str,before,after,removed);
// "qd ezrwsvra etxced"
如果您需要用另一个字符串替换子字符串,您可以使用下一个函数:
function replaceSubstring(str,before,after,removed,inserted){
var rg=new RegExp("("+before+")("+removed+")("+after+")","gi");
return str.replace(rg,function($0,$1,$2,$3){
// $1 is searched "before" substring
// $2 is searched "removed" substring
// $3 is searched "after" substring
return $1+(inserted||"")+$3;
});
};
var str="qXd ezrwsvrVa etxceZd";
var before="q|w|e|r";
var after="a|s|d|f";
var removed="z|x|c|v";
replaceSubstring(str,before,after,removed,"DDDD")
// "qDDDDd ezrwsvrDDDDa etxceDDDDd"