1

I want to have a prompt box asking the user for their name. But I'm putting that directly into the page, and if I enter something HTML-y (<canvas> for example) then it places that element on the page. How can I make this into text, so instead of making a <canvas> element it writes <canvas> to the page as text?

var name = prompt("Enter your name: ");
document.getElementById("paragraph").innerHTML = name;
<p id="paragraph"></p>

Unfortunately I can't use jQuery, so a pure JS solution would be nice.

Jack Bashford
  • 40,575
  • 10
  • 44
  • 74

2 Answers2

1

You can use innerText, instead of innerHTML

 document.getElementById("paragraph").innerText = name;
Mesar ali
  • 1,654
  • 2
  • 14
  • 18
0

You want to 'escape' the input text before displaying it again.

Your JavaScript would now look like:

var name = escapeHtml(prompt("Enter your name: "));
document.getElementById("paragraph").innerHTML = name;

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

Note: This code snippet is from Can I escape html special chars in javascript?

PSA: Please don't use client-side sanitation of text for anything related to security.

Arthur-1
  • 245
  • 1
  • 7