如何基于javascript中的规则对字符串应用正则表达式?

如何基于javascript中的规则对字符串应用正则表达式?,javascript,regex,Javascript,Regex,我有一根像这样的线 str = "<span> list: <mat> </span> && <span> see: how much <mat> </span> && <span> with: <mat> = '<pok>'</span>" 但它将的每个实例替换为<和>。regex是否可以有一个规则,除了标记之外,其他所有需要替换的东

我有一根像这样的线

str = "<span> list: <mat> </span> && <span> see: how much <mat> </span> && <span> with: <mat> = '<pok>'</span>"
但它将
的每个实例替换为
<
>
regex
是否可以有一个规则,除了
标记之外,其他所有需要替换的东西都可以被替换?

我会匹配
]+>
(a
),然后如果当前匹配不是
,则使用替换函数来转义括号:

const str=“列表:&&see:how money&&with:=”;
const escape=str=>str
.替换(//g,“>”);
const result=str.replace(
/]+>/g,,
匹配=>(匹配==''| |匹配=='')?匹配:转义(匹配)
);

控制台日志(结果)根据您支持的浏览器,您可以使用负面lookaheads和lookbehinds来匹配您的
span
标记:

str.replace(/<(?!(\/?span))/g,'&lt;').replace(/(?<!\/?span)>/g, '&gt;')
str.replace(/
?!
是一种负前瞻,它告诉正则表达式引擎仅在以下文本与该表达式不匹配时才匹配(例如,“如果

str.replace(/<(?!(\/?span))/g,'&lt;').replace(/(?<!\/?span)>/g, '&gt;')