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:
<script>alert(1)</script>
Tom & Jerry'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
<script>alert(1)</script> Tom & Jerry's
Example 2 · Input
<img src=x onerror="alert(1)">
Expected output
<img src=x onerror="alert(1)">
Hints
Hint 1
Chain .replace(/&/g, "&").replace(/</g, "<") 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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"));
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step