Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping HTML strings with jQuery

Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.

like image 647
Page Avatar asked Aug 24 '08 02:08

Page


People also ask

How do I escape HTML data?

Skipping > can potentially break code. You must keep in mind that inside the <> is also html. In that case skipping > will break. If you're only escaping for between tags then you probably only need escape < and &.

What is parseHTML in JavaScript?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).


1 Answers

There is also the solution from mustache.js

var entityMap = {   '&': '&amp;',   '<': '&lt;',   '>': '&gt;',   '"': '&quot;',   "'": '&#39;',   '/': '&#x2F;',   '`': '&#x60;',   '=': '&#x3D;' };  function escapeHtml (string) {   return String(string).replace(/[&<>"'`=\/]/g, function (s) {     return entityMap[s];   }); } 
like image 153
Tom Gruner Avatar answered Oct 05 '22 23:10

Tom Gruner