[SOLVED] What is the HtmlSpecialChars equivalent in JavaScript?

Issue

This Content is from Stack Overflow. Question asked by xaaaaaaaaaaaa

There’s a way to replace only some HTML tags with JQuery / JavaScript?

For all tags substitution can be used this function found over stackoverflow.com.

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

But if I want replace only some HTML tags in a text (also nested) what have I do?

Regex for nested tags it’s out of the game.

Something like a DOM parser could be this.

If #idname it’s a textarea here the start code

var doNoSubstituteArray = ['br','div'];
let htmlString = $('#idname').val();
let htmlDoc = (new DOMParser()).parseFromString(htmlString, "text/html");
let tags = htmlDoc.getElementsByTagName('*');

But then?

How to replace only some tags (specified in doNoSubstituteArray)?



Solution

There is a problem with your solution code–it will only escape the first occurrence of each special character. For example:

escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual:   Kip&#039;s &lt;b&gt;evil</b> &quot;test" code's here
Expected: Kip&#039;s &lt;b&gt;evil&lt;/b&gt; &quot;test&quot; code&#039;s here

Here is code that works properly:

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

Update

The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks jbo5112).

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  
  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}


This Question was asked in StackOverflow by Bart van Heukelom and Answered by Kip It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?