在特殊标记之外使用javascript正则表达式替换?

时间:2012-08-11 12:00:29

标签: javascript regex

我想使用javascript替换(删除)[code] bbcode之外的html标签。例如:

 <script>these</script> [code]<script>alert</script>[/code]<script>that</script>

应该成为

 these [code]<script>alert</script>[/code]that

如何使用RegEx替换/删除[code]之外的标签?

2 个答案:

答案 0 :(得分:3)

将此/(\[code\][\s\S]*?\[\/code\])|<[\s\S]*?>/g替换为$1

your_string.replace(/(\[code\][\s\S]*?\[\/code\])|<[\s\S]*?>/g, '$1');

它会首先找到所有[code]个标签,保存它们,之后它会找到剩余的html标记(位于[code]标记中)

答案 1 :(得分:-2)

好的我找到了解决方案:

replace(/<(?=[^\[]*\[\/code\])/gi,"&_lt_;");
replace(/>(?=[^\[]*\[\/code\])/gi,"&_gt_;");

DO OTHER REPLACEMENT/CUSTOMIZATION HERE

replace(/&_lt_;/gi,"<");
replace(/&_gt_;/gi,">");
那个! :)