[英]Escape html, except when inside [code] [/code] tags
我想解析一個字符串並將其輸出,執行以下操作:
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
如何識別標簽內部/外部的字符串? 我不需要存儲字符串,只需處理它們並輸出即可。
非常感謝
我在下面編寫了一個示例,該示例在[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, '&').replace(/</g, '<').replace(/>/g, '>');
}
}
string = tempString.join("")
alert(string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.