Search code examples
sveltehtml-escape-characters

Display html characters in Svelte


I have a Svelte app REPL where I wish to convert strings to html characters.

<h1>Test html codes</h1>
{#each lines|| [] as line}
    <div id="comment-line">
        {line}
    </div>
{/each}


<script>
    let rawData = [
        'Abc',
        'Xyz!tm',
        'Mno'
    ]
    $: lines = parseLines(rawData)
    
    function parseLines(array) {
        let new_array = []
        var new_line
        for (var line of array) {
            new_line = line.replaceAll('!tm', '&trade;');
            new_array.push(new_line)
        }
        return new_array
    }
</script>

This answer suggests that you use .innerHTML, but can it be done in a more straightforward way in Svelte?


Solution

  • In Svelte you can use {@html line} which will output line as pure html getting the effect you require. Be aware though that is inherently insecure and should only be done with strings you absolutely trust and likely never with user-generated content. (if the string contains a script it will run it for example)

    Alternatively consider doing new_line = line.replaceAll('!tm', '™'); instead.