Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest method to escape HTML tags as HTML entities?

I'm writing a Chrome extension that involves doing a lot of the following job: sanitizing strings that might contain HTML tags, by converting <, > and & to &lt;, &gt; and &amp;, respectively.

(In other words, the same as PHP's htmlspecialchars(str, ENT_NOQUOTES) – I don't think there's any real need to convert double-quote characters.)

This is the fastest function I have found so far:

function safe_tags(str) {     return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') ; } 

But there's still a big lag when I have to run a few thousand strings through it in one go.

Can anyone improve on this? It's mostly for strings between 10 and 150 characters, if that makes a difference.

(One idea I had was not to bother encoding the greater-than sign – would there be any real danger with that?)

like image 991
callum Avatar asked Mar 31 '11 11:03

callum


People also ask

How do you escape HTML tags in HTML?

Escape characters will always begin with the ampersand symbol (&) and end with a semicolon symbol (;). The characters in between the ampersand and semicolon make up the specific code name or number for a particular character.

What is escaping HTML?

Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML. Imagine, you write <b>hello, world</b> And the text will appear as hello, world.


1 Answers

Here's one way you can do this:

var escape = document.createElement('textarea'); function escapeHTML(html) {     escape.textContent = html;     return escape.innerHTML; }  function unescapeHTML(html) {     escape.innerHTML = html;     return escape.textContent; } 

Here's a demo.

like image 134
Web_Designer Avatar answered Oct 11 '22 06:10

Web_Designer