Coder Perfect

Is it possible to escape HTML special characters in JavaScript?


I’d like to use a JavaScript method to convert text to HTML. In JavaScript, how can I escape HTML special characters? Is there a programmatic interface (API)?

Asked by fernando123

Solution #1

Here’s a workaround that should work in almost every web browser:

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

You can use the new replaceAll function if you only support contemporary web browsers (2020+):

const escapeHtml = (unsafe) => {
    return unsafe.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;');

Answered by bjornd

Solution #2

Answered by spiderlama

Solution #3

The.text() function in jQuery can be used.

For example:

The following is taken from the jQuery documentation for the.text() function:

Previous Versions of the jQuery Documentation worded it this way (emphasis added):

Answered by jeremysawesome

Solution #4

Using Lodash:

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

Source code

Answered by cs01

Solution #5

I believe I’ve figured out how to do it properly…

// 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:

Answered by lvella

Post is based on