0

How do I update the below code to escape HTML and strings in JavaScript arrays. I am trying to use a function escapeHtml to add the slashes but it won't execute as intended. Thanks

<!DOCTYPE html>
<html>
<body>


<p id="demo"></p>

<script>
function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }
var unsafe = ["car's", "<h1>hello</h1>", "Ref#1", "a-b", "he said "hello" to him"];
document.getElementById("demo").innerHTML = escapeHtml(unsafe);
</script>

</body>
</html>
User301276
  • 55
  • 1
  • 8

1 Answers1

2

You have to call escapeHtml for each element in array:

document.getElementById("demo").innerHTML = unsafe.map(a => escapeHtml(a));
munleashed
  • 1,677
  • 1
  • 3
  • 9