I need HTML ENCODE in JavaScript (client side) a String (where User could insert HTML TAGS) from a TextBox so bypassing Reqeust.Validation.
Javascript should Encode string and Display it Encoded in Label.
<asp:TextBox ID="uxValueInput" runat="server"></asp:TextBox>
<br />
<asp:Label ID="uxResultEncoded" runat="server" Text="Label"></asp:Label>
<asp:Button ID="uxEncodeButton" runat="server" Text="Button" />
I am new in JavaScript and I have tried different scripts on a web but with no success. Could you please post a really simple example so I would be able to understand how could work. Thanks!
I'm with David Dorland: Don't do this client-side, instead disable request validation ( here's an article saying how ). But if you do that, be sure you also use Anti-XSS or similar libraries to prevent exactly what it is that ASP.Net is trying to protect you from.
However, if you have a genuine use-case for doing minimal HTML-encoding on the client, you can do this:
var escapes = {
'<': '<',
'>': '>',
'&': '&'
};
var raw = "Hi, I'm an <scr" + "ipt src='http://evil.example.com/attack.js'><\/script> evil & malicious attack.";
var encoded = raw.replace(/[<>&]/g, function(m) {
return escapes[m];
});
Here's how that works:
escapes
which maps the raw character to the HTML entity for it (so maps <
to <
, etc.). String#replace
and a regular expression to search for all <
, >
, and &
characters and replace them with their equivalent entity. When you pass a function into String#replace
as the second argument, it gets called for each match and uses the return value as the replacement. The regex, /[<>&]/g
, means "find <
, >
, or &
globally (the g
flag) within the string".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.