jQuery 过滤html标签属性的特殊字符

html-css04

jQuery 过滤html标签属性的特殊字符,第1张

您好,如果在表单中需要提交一字符串,其中包含,<>" &字符时,当我们把这字符串显示到jsp页面时,会和html标签产生冲突,导致web页面的某些部分消失或者格式不正确。为了解决以上问题,需要在显示之前,对字符串进行代码过滤。

把字符串中的 < 替换为 &It

> 替换为 >

" 替换为 "

& 替换为 &

这里给出一个静态的过滤代码,供大家参考:

public class StringUtils {

/**

* This method takes a string which may contain HTML tags (ie, <b>,

* <table>, etc) and converts the '&lt'' and '>' characters to their HTML escape sequences.

* @param input the text to be converted.

* @return the input string with the characters '<' and '>' replaced with their HTML escape sequences.

*/

public static final String escapeHTMLTags(String input) {

//Check if the string is null or zero length -- if so, return

//what was sent in.

if (input == null || input.length() == 0) {

return input

}

//Use a StringBuffer in lieu of String concatenation -- it is

//much more efficient this way.

StringBuffer buf = new StringBuffer(input.length())

char ch = ' '

for (int i = 0i <input.length()i++) {

ch = input.charAt(i)

if (ch == '<') {

buf.append("<")

}

else if (ch == '>') {

buf.append(">")

}else if(ch == '"'){

buf.append(""")

}else if(ch == '&'){

buf.append("&")

}

else {

buf.append(ch)

}

}

return buf.toString()

}

}

此时,只需在jsp中对字符串调用此方法(StringUtils.escapeHTMLTags(str))即可。

其实显示的时候用server.HTMLEncode(str)就能把str编码。

如果要过滤掉html内容的话,就要在添加到数据库的时候过滤,用正则表达式是个不错的主意。

Function RemoveHTML(strHTML)

Dim objRegExp, Match, Matches

Set objRegExp = New Regexp

objRegExp.IgnoreCase = True

objRegExp.Global = True

'取闭合的<>

objRegExp.Pattern = "<.+?>"

'进行匹配

Set Matches = objRegExp.Execute(strHTML)

' 遍历匹配集合,并替换掉匹配的项目

For Each Match in Matches

strHtml=Replace(strHTML,Match.Value,"")

Next

RemoveHTML=strHTML

Set objRegExp = Nothing

End Function