2023-09-18

 18 Sep 2023

Convert Characters to HTML Entities

Taken from FreeCodeCamp

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

Solution

This is the answer I came up with:

function convertHTML(str: string): string {

    function entitize(char: string) {
        switch (char) {
            case '"': {
                return '&quot;'
                break
            }
            case '&': {
                return '&amp;'
                break
            }
            case '<': {
                return '&lt;'
                break
            }
            case '>': {
                return '&gt;'
                break
            }
            case '\'': {
                return '&apos;'
                break
            }
            default: {
                return char
            }
        }
    }

    let result = [],
        strlen = str.length

    for (let i = 0; i < strlen; i++) {
        result.push(entitize(str[i]))
    }

    return result.join('')
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABBBA3ApgJygCQCoCyAMgBQDOUmAXIhZjGAOYCUNdDjiA3gFA+IDEoSLASJ0YWLABe6EhAAWAQ2q1KHZt36CdZAO4woixPOWZNvHVcEQlZdIgDkAIkc1L1zwMzooITEiOAGQAjiBwUADcjtpe1gBGPkoA1rFxAL5pXrb2TkFuWnGePn4BeUoAtgAO0VlFiInoKXXWmfXIdg6OADwFHu3evv6BQQA2UTEDgo3N7W31OV0AfH0tcSXDeYwTa14zqXO7Np1OADqOq1ODpSNKVXBktVcNSQf180UAJujASiDj7iO1g2ZUUKiBiA+VihmTSo18iB8ZH+UEQAF5EABtAC6ABo1nR4UgMXQAHRE7YKPg6YBwTAmeGomDoxAABkiiGZ3TUmCJHJgAGoBRY1kiUaSqiAyAoSBIpDBZORKJiYNjmMw0rCdCCkGLxqSAFZwBgkC4a2EoMBkODw8lwRgkNKWjDYfDEEjOAAiNogDiCiAA4kp4vElGAlM5mLjEAB6GOIb2jX2IIKVGqB4Oh8NOtBYXCEUjOHCVeL+RhYMiIbkABQV0iUVcQeCUKDIkejccQxYqpcw5cwlbGUUQtek9ZT4w5zdbObALvz7ucAGUYAAPKAAT0QS0QUD06FGGHbsfjK-XW6C2w5e4PGFn87dpEcS78wGAnKQzjCESUoiQFRUZI20cKMT0QF8QDfD8U2-KJYN-eB-0AshQnCKJ7zzR8PSXRQGE+eFMEcSsiBgChj07HCFDwgjU3uR5iNIqAMNdAsPW6JZIzAodIkvdCNSAA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems