JS - Sanitize object (strings) + serialize

by Zacc206

HTML

<div>
  <button>Run script</button>
</div>

<h3>Unsafe results</h3>
<div id="results-unsafe">
 No results
</div>

<h3>Sanitized results</h3>
<div id="results-safe">
 No results
</div>

CSS

body {font-family: sans-serif;}
body * {font-size: 14px;}

JavaScript

document.getElementsByTagName("button")[0].onclick = run;

function run(){
	var obj = {
  	'key1': "safe",
    'key2': "safe",
    'key3': "un<safe>"
  };
  
  // Serialize unsanitized object
  document.getElementById("results-unsafe").innerText = JSON.stringify(obj);
  // Serialize sanitized object
  document.getElementById("results-safe").innerText = JSON.stringify(sanitizeObj(obj));
}

function sanitizeObj(obj){
  for(var key in obj){
    if(obj.hasOwnProperty(key)){
      if(typeof obj[key] === "string"){
        obj[key] = escapeHtml(obj[key]);
      }
    }
  }
  return obj;
}

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