settingsAccountsettings
Menusettings

Q: Escaping - escape special HTML characters in JavaScript

+2 votes

You will be given a list of strings, containing user-submitted data. Write a JS function that prints an HTML list from the data.

The strings, however, may contain special HTML characters, which is an oft-used method for injection attacks. To prevent unwanted behavior or harmful content, all special characters need to be replaced with their encoded counterparts – they will look the same to the user, but will not pose a security risk. Use the following table to compose your function:

Raw

Encoded

<

>

&

&

"

"

 

Use the provided HTML template to visually test your code – if you don’t escape the control characters, formatted HTML will show up. Don’t care how the HTML template works. Your job is to write the JS escaping function only.

The input comes as array of string elements.

Examples:

Input:
['<b>unescaped text</b>', 'normal text']

Output:
<ul>
  <li>&lt;b&gt;unescaped text&lt;/b&gt;</li>
  <li>normal text</li>
</ul>


Input:
['<div style=\"color: red;\">Hello, Red!</div>', '<table><tr><td>Cell 1</td><td>Cell 2</td><tr>']

Output:
<ul>
  <li>&lt;div style=\&quot;color: red;\&quot;&gt;Hello, Red!&lt;/div&gt;</li>
  <li>&lt;table&gt;&lt;tr&gt;&lt;td&gt;Cell 1&lt;/td&gt;&lt;td&gt;Cell 2&lt;/td&gt;&lt;tr&gt;</li>
</ul>

The output is the return value of your function. Compose the list in a string and return it. See the examples for formatting details.

asked in JavaScript category by user richard8502

2 Answers

0 votes
 
Best answer

HTML escaping can be done with this JavaScript code:

function htmlEscape(text) {
    let map = {
        '"': '&quot;', '&': '&amp;',
        "'": '&#39;', '<': '&lt;', '>': '&gt;'
    };
    return text.replace(/[\"&'<>]/g, ch => map[ch]);
}

This is my js code for the task:

function printList(items) {
    return "<ul>\n" +
        items.map(htmlEscape).map(
                item => `  <li>${item}</li>`).join("\n") +
        "\n</ul>\n";

    function htmlEscape(text) {
        let map = {
            '"': '&quot;', '&': '&amp;',
            "'": '&#39;', '<': '&lt;', '>': '&gt;'
        };
        return text.replace(/[\"&'<>]/g, ch => map[ch]);
    }
}

console.log(printList(['<div style=\"color: red;\">Hello, Red!</div>', '<table><tr><td>Cell 1</td><td>Cell 2</td><tr>']));

 

answered by user golearnweb
edited by user golearnweb
+1 vote

Here is my JavaScript solution:

function htmlList(items) {
    console.log("<ul>");
    for (let item of items) {
        console.log("    <li>" + htmlEscape(item) + "</li>");
    }
    console.log("</ul>");

    function htmlEscape(text) {
        let map = {
            '"': '"', '&': '&amp;',
            "'": '&#39;', '<': '<', '>': '>'
        };
        return text.replace(/[\"&'<>]/g, ch => map[ch]);
    }
}

console.log(htmlList(['<b>unescaped text</b>', 'normal text']));

 

answered by user andrew
edited by user golearnweb
...