Can I avoid html special characters in javascript?

I want to display text in HTML using javascript function. How can I avoid html special characters in JS? Is there an API?

+161
javascript html
Jun 04 '11 at 4:50
source share
14 answers
function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); } 
+273
Jun 04 '11 at 5:00
source share

You can use jQuery .text() function .

For example:

http://jsfiddle.net/9H6Ch/

From the jQuery documentation regarding the .text() function:

We need to know that this method avoids the string if necessary so that it displays correctly in HTML. To do this, it calls the DOM.createTextNode () method, does not interpret the string as HTML.

Previous versions of jQuery documentation are worded as follows (highlighted by me):

We need to know that this method avoids the string if necessary so that it displays correctly in HTML. To do this, it calls the DOM.createTextNode () method, which replaces special characters with its equivalent HTML entities (for example, & lt; for <).

+46
Jun 04 2018-11-11T00:
source share

 function escapeHtml(html){ var text = document.createTextNode(html); var p = document.createElement('p'); p.appendChild(text); return p.innerHTML; } // Escape while typing & print result document.querySelector('input').addEventListener('input', e => { console.clear(); console.log( escapeHtml(e.target.value) ); }); 
 <input style='width:90%; padding:6px;' placeholder='&lt;b&gt;cool&lt;/b&gt;'> 
+46
Aug 20 '14 at 2:50
source share

I guess I found the right way to do this ...

 // Create a DOM Text node: var text_node = document.createTextNode(unescaped_text); // Get the HTML element where you want to insert the text into: var elem = document.getElementById('msg_span'); // Optional: clear its old contents //elem.innerHTML = ''; // Append the text node into it: elem.appendChild(text_node); 
+24
Aug 07 '13 at 16:16
source share

Using lodash

 _.escape('fred, barney, & pebbles'); // => 'fred, barney, &amp; pebbles' 

source

+23
Oct 30 '16 at 19:41
source share

This is by far the fastest way I've seen this. In addition, all this is done without adding, deleting, or changing elements on the page.

 function escapeHTML(unsafeText) { let div = document.createElement('div'); div.innerText = unsafeText; return div.innerHTML; } 
+20
Jan 02 '18 at 0:11
source share

It was interesting to find the best solution:

 var escapeHTML = function(unsafe) { return unsafe.replace(/[&<"']/g, function(m) { switch (m) { case '&': return '&amp;'; case '<': return '&lt;'; case '"': return '&quot;'; default: return '&#039;'; } }); }; 

I do not parse > because it does not violate the XML / HTML code as a result.

Here are the criteria: http://jsperf.com/regexpairs Also I created a generic escape function: http://jsperf.com/regexpairs2

+11
Feb 11 '15 at 15:41
source share

The shortest and most effective way to display unencoded text is to use the textContent property.

Faster than using innerHTML . And this is without taking into account the possibility of avoiding overhead costs.

 document.body.textContent = 'a <b> c </b>'; 

+5
Nov 29 '17 at 2:57
source share

DOM Elements supports converting text to HTML by assigning innerText . innerText is not a function, but assigning it to it works as if the text was escaped.

 document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>'; 
+4
Aug 21 '17 at 10:27
source share

You can encode each character in a string:

 function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})} 

Or just aim for the main characters to worry (&, inebreaks, <,>, "and '), for example:

 function encode(r){ return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"}) } test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!'); /************* * \x26 is &ampersand (it has to be first), * \x0A is newline, *************/ 
 <textarea id=test rows="9" cols="55">&#119;&#119;&#119;&#46;&#87;&#72;&#65;&#75;&#46;&#99;&#111;&#109;</textarea> 
+2
Jul 26 '15 at 13:54 on
source share

I came across this problem when building a DOM structure. This question helped me solve it. I wanted to use double chevron as a path separator, but adding a new text node directly led to the display of the code of the escaped character, and not the character itself:

 var _div = document.createElement('div'); var _separator = document.createTextNode('&raquo;'); //_div.appendChild(_separator); /* this resulted in '&raquo;' being displayed */ _div.innerHTML = _separator.textContent; /* this was key */ 
0
Jul 30 '19 at 8:36
source share

Try this using the prototype.js library:

 string.escapeHTML(); 

Try the demo

-3
Apr 16 '14 at 20:48
source share

I came up with this solution.

Suppose we want to add some html to an element with insecure data from a user or database.

 var unsafe = 'some unsafe data like <script>alert("oops");</script> here'; var html = ''; html += '<div>'; html += '<p>' + unsafe + '</p>'; html += '</div>'; element.html(html); 

This is unsafe for XSS attacks. Now add this.

 $(document.createElement('div')).html(unsafe).text(); 

So this is

 var unsafe = 'some unsafe data like <script>alert("oops");</script> here'; var html = ''; html += '<div>'; html += '<p>' + $(document.createElement('div')).html(unsafe).text(); + '</p>'; html += '</div>'; element.html(html); 

This is much easier for me than using .replace() , and it will delete !!! all possible html tags (hopefully).

-3
Mar 30 '16 at 9:53 on
source share

I'm not quite sure if this is what you mean, but you can avoid the html characters in the string variable as follows:

 var string = escape("escaped lessthan looks like this <"); 

which sets the string == to escaped%20lessthan%20looks%20like%20this%20%3C

-four
Jun 04 2018-11-11T00:
source share



All Articles