What is the HtmlSpecialChars equivalent in JavaScript? What is the HtmlSpecialChars equivalent in JavaScript? javascript javascript

What is the HtmlSpecialChars equivalent in JavaScript?


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 <b>evil</b> "test" code's hereExpected: Kip&#039;s <b>evil</b> "test" code&#039;s here

Here is code that works properly:

function escapeHtml(text) {  return text      .replace(/&/g, "&")      .replace(/</g, "<")      .replace(/>/g, ">")      .replace(/"/g, """)      .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 = {    '&': '&',    '<': '<',    '>': '>',    '"': '"',    "'": '&#039;'  };    return text.replace(/[&<>"']/g, function(m) { return map[m]; });}


That's HTML Encoding. There's no native javascript function to do that, but you can google and get some nicely done up ones.

E.g. http://sanzon.wordpress.com/2008/05/01/neat-little-html-encoding-trick-in-javascript/

EDIT:
This is what I've tested:

var div = document.createElement('div');  var text = document.createTextNode('<htmltag/>');  div.appendChild(text);  console.log(div.innerHTML);

Output: <htmltag/>


Worth a read:http://bigdingus.com/2007/12/29/html-escaping-in-javascript/

escapeHTML: (function() { var MAP = {   '&': '&',   '<': '<',   '>': '>',   '"': '&#34;',   "'": '&#39;' };  var repl = function(c) { return MAP[c]; };  return function(s) {    return s.replace(/[&<>'"]/g, repl);  };})()

Note: Only run this once. And don't run it on already encoded strings e.g. & becomes &amp;