Escape for HTML

Output encoding keeps text as text: the characters HTML treats specially are replaced with entities before the text goes into a page.

What to build

Escape each line for safe use inside HTML.

Requirements

  • Replace & with & first, then < with <, > with >, " with " and ' with '.
  • Print each escaped line.

Input

Lines of text.

Output

Each line, escaped.

Constraints

1 to 30 lines of up to 200 characters.

Example

Input:

<script>alert(1)</script>
Tom & Jerry's

Output:

&lt;script&gt;alert(1)&lt;/script&gt;
Tom &amp; Jerry&#39;s

Why it works

Replacing & first stops the & of the other entities from being escaped again; after that, no character in the text can start a tag or end an attribute.

Examples

Example 1 · Input
<script>alert(1)</script>
Tom & Jerry's
Expected output
&lt;script&gt;alert(1)&lt;/script&gt;
Tom &amp; Jerry&#39;s
Example 2 · Input
<img src=x onerror="alert(1)">
Expected output
&lt;img src=x onerror=&quot;alert(1)&quot;&gt;

Hints

Hint 1

Chain .replace(/&/g, "&amp;").replace(/</g, "&lt;") and so on, in that order.

Solution

Show one correct solution (try it yourself first)
let line = prompt();
while (line !== null) {
  console.log(line.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"));
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Cross-site scripting (XSS) →