1、定义正则表达式:
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi
2、用正则表达式处理script的方法如下:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".btn1").click(function(){
alert($("p").html())
})
})
</script>
<!--此处引入script脚本用于测试结束-->
</head>
<body>
<p>This is a paragraph.</p>
<!--这里增加一个按钮,点击后会删除所有的script块的代码-->
<button class="btn1" onclick="removeAllScript()">删除script</button>
</body>
</html>
<!--定义function处理删除-->
function removeAllScript(obj){
//定义正则表达式,只要是存在于<script>和</script>之间的内容都会被删除
var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi
while (SCRIPT_REGEX.test(obj)) {//传入文档对象,获取整体内容
text = text.replace(SCRIPT_REGEX, "")//正则替换为空
}
}
public static string NoHtml(string text){
//删除脚本
text = Regex.Replace(text, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase)
//删除HTML
text = Regex.Replace(text, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"-->", "", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"<!--.*", "", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(quot|#34)", "\"", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(amp|#38)", "&", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(lt|#60)", "<", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(gt|#62)", ">", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(nbsp|#160)", " ", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(iexcl|#161)", "\xa1", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(cent|#162)", "\xa2", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(pound|#163)", "\xa3", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"&(copy|#169)", "\xa9", RegexOptions.IgnoreCase)
text = Regex.Replace(text, @"(\d+)", "", RegexOptions.IgnoreCase)
text.Replace("<", "")
text.Replace(">", "")
text.Replace("\r\n", "")
text = HttpContext.Current.Server.HtmlEncode(text).Trim()
return text
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)