我想解析一个字符串并输出它,执行以下操作:
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
如何识别标签内/外的字符串?我不需要存储字符串片段,只需要处理它们并输出。
非常感谢
发布于 2018-01-28 23:09:49
下面我编写了一个示例,在[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)
这个演示也可以在小提琴上播放。
https://stackoverflow.com/questions/48491640
复制相似问题