Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I escape HTML special chars in JavaScript?

I want to display text to HTML by a JavaScript function. How can I escape HTML special characters in JavaScript? Is there an API?

like image 421
fernando123 Avatar asked Jun 04 '11 04:06

fernando123


People also ask

Can I escape HTML special characters in JavaScript?

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 &.

Can I escape HTML special characters?

We can escape the HTML of the string using the replace method of the string.

How do you escape text in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.


2 Answers

Here's a solution that will work in practically every web browser:

function escapeHtml(unsafe) {     return unsafe          .replace(/&/g, "&amp;")          .replace(/</g, "&lt;")          .replace(/>/g, "&gt;")          .replace(/"/g, "&quot;")          .replace(/'/g, "&#039;");  } 

If you only support modern web browsers (2020+), then you can use the new replaceAll function:

const escapeHtml = (unsafe) => {     return unsafe.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;'); } 
like image 140
bjornd Avatar answered Oct 19 '22 17:10

bjornd


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;'>
like image 35
spiderlama Avatar answered Oct 19 '22 18:10

spiderlama