JavaScript - HTML Entities



Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.


/*
case & : &amp
case < : &lt
case > : &gt
case " : &quot
case ' : &apos
*/

Solution Basic approach


function convertHTML(str) {

    var index = str.split("")

    for (var i = 0; i < index.length; i++) {
        if (index[i] === "&") {
            index[i] = "&amp;"
        }
        if (index[i] === "<") {
            index[i] = "&lt;"
        }
        if (index[i] === ">") {
            index[i] = "&gt;"
        }
        if (index[i] === "'") {
            index[i] = "&apos;"
        }
        if (index[i] === '"') {
            index[i] = "&quot;"
        }
    }
    return index.join("");
}

console.log(convertHTML("Dolce & Gab<bana"));
console.log(convertHTML("Hamburgers < Pizza < Tacos"));

Output:


Dolce & Gab<bana
Hamburgers < Pizza < Tacos

Solution not working or have any suggestions? Please send an email to [email protected]



Join Our Facebook Group


Share this example


Download Android App

download android app

Popular javascript Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube