I. html encoding and decoding of characters in Asp.net
Character HTML encoding:
System. Web. httputility. htmlencode ( " String " );
Character HTML Decoding:
Message = Page. server. htmldecode ( " String " );
Ii. html encoding and decoding in JS
There are two methods to achieve this. One is implemented by assigning a value to a dynamically created container, and the other is implemented by replacing special characters.
1. by assigning a value to a dynamic container
1) HTML encoding:
This method is implemented using the internal converter of the browser. The method is to dynamically create a container tag element, such as Div, and set the string to be converted to the innertext of this element, then, the innerhtml of the element is returned to obtain the HTML-encoded string.
Code Function Htmlencode (input)
{
VaR Converter = Document. createelement ( " Div " );
Converter. innertext = Input;
VaR Output = Converter. innerhtml;
Converter = Null ;
Return Output;
}
2) HTML Decoding:
The same method is used to decode the htmldecode of the string, but the problem is that non-null characters following the character "<" will not be displayed together with the character "<. However, corresponding processing of the string can solve this problem. For example, add a space after the character "<" and then remove it After decoding. After all, to use the htmldecode decoding method, the character string has been encoded by the htmlencode method, and the character string after htmlencode encoding cannot have the character "<.
Function Htmldecode (input)
{
VaR Converter = Document. createelement ( " Div " );
Converter. innerhtml = Input;
VaR Output = Converter. innertext;
Converter = Null ;
Return Output;
}
2. By replacing special characters
1) HTML encoding:
Function Htmlencode (STR)
{
VaR S = "" ;
If (Str. Length = 0 ) Return "" ;
S = Str. Replace ( / & / G, " & Gt; " );
S = S. Replace ( / < / G, " & Lt; " );
S = S. Replace ( / > / G, " & Gt; " );
S = S. Replace ( / / G, "& nbsp ;");
S = S. Replace ( / \' / G, " ' " );
S = S. Replace ( / \" / G, " & Quot; " );
S = S. Replace ( / \ N / G, " <Br> " );
Return S;
}
2) HTML Decoding:
Function Htmldecode (STR)
{
VaR S = "" ;
If (Str. Length = 0 ) Return "" ;
S = Str. Replace ( / & Gt; / G, " & " );
S = S. Replace ( / & Lt; / G, " < " );
S = S. Replace ( / & Gt; / G, " > " );
S = S. Replace ( / & Nbsp; / G, " " );
S = S. Replace ( / ' / G, " \' " );
S = S. Replace ( / & Quot; / G, " \ "" );
S = S. Replace (/<br>/g, " \ N " );
Return S;
}
Note: In the second part of this article, "HTML encoding and decoding in JS" is converted from http://hi.baidu.com/hfgyd2616/blog/item/864becf8cbe52c0bd9f9fdd9.html