Question #6887   Submitted by Answiki on 10/12/2022 at 01:38:56 PM UTC

In JavaScript, how to escape HTML characters?

Answer   Submitted by Answiki on 10/12/2022 at 01:40:07 PM UTC

The following JavaScript code is used to convert special characters into HTML entities:

var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}


Here is the result:

var before="\" \' & < > =";
var after = escapeHtml(before);

// Affiche "Before : " ' & < > ="
console.log ("Before : " + before);
// Affiche : "After : " &#39; & < > &#x3D;"
console.log ("After : " + after);

Try online on JSFiddle.


Source : Escaping HTML strings with jQuery

3 events in history
Answer by Answiki on 10/12/2022 at 01:40:07 PM

The following JavaScript code is used to convert special characters into HTML entities:

var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}


Here is the result:

var before="\" \' & < > =";
var after = escapeHtml(before);

// Affiche "Before : " ' & < > ="
console.log ("Before : " + before);
// Affiche : "After : " &#39; & < > &#x3D;"
console.log ("After : " + after);

Try online on JSFiddle.


Source : Escaping HTML strings with jQuery

Answer by Answiki on 10/12/2022 at 01:39:57 PM

The following JavaScript code is used to convert special characters into HTML entities:

var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}


Here is the result:

var before="\" \' & < > =";
var after = escapeHtml(before);

// Affiche "Before : " ' & < > ="
console.log ("Before : " + before);
// Affiche : "After : " &#39; & < > &#x3D;"
console.log ("After : " + after);

Try online on JSFiddle.


Source : Escaping HTML strings with jQuery



Question by Answiki 10/12/2022 at 01:38:56 PM
In JavaScript, how to escape HTML characters?
# ID Query URL Count

Icons proudly provided by Friconix.