转义 html,除非在 [code] [/code] 标签内

Escape html, except when inside [code] [/code] tags

我想解析一个字符串并输出它,执行以下操作:

如何识别字符串 inside/outside 的标签?我不需要存储字符串片段,只需对其进行处理并输出即可。

非常感谢

我在下面写了一个示例,它在 [code][/code] 标签处拆分字符串,然后转义所有不在这些标签之间的 html ,然后将该数组放回字符串中,使用join 命令。

请注意,如果缺少 [code] 标签之一,程序将出现意外行为。

string = "hello world<b>this is mohammad's amazing code:</b> [code]<br>mohammad<br>is<br>amazing[/code]<br>"
tempString = string.split(/(\[code\])(.+)(\[\/code\])/g)

var isCode = 0
for (var i = 0; i < tempString.length; ++i) {
  if (tempString[i].match(/(\[code\])/g)) {
    //code begins here
    isCode = 1
  } else if (tempString[i].match(/(\[\/code\])/g)) {
    //code ends here
    isCode = 0
  }
  if (isCode == 0) {
    tempString[i]=tempString[i].replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }
}
string = tempString.join("")
alert(string)

此演示也可以在 jsfiddle

上播放