簡體   English   中英

轉義html,除非在[code] [/ code]標記內

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

我想解析一個字符串並將其輸出,執行以下操作:

  • 轉義html-例如:
    • return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  • [code] [/ code]標記內的文字除外
  • 為字符串中的多個代碼標簽工作

如何識別標簽內部/外部的字符串? 我不需要存儲字符串,只需處理它們並輸出即可。

非常感謝

我在下面編寫了一個示例,該示例在[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播放

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM