Svelte – Convert string into HTML

Total
0
Shares
Table of Contents Hide
  1. Code Example
  2. Live Demo

It is one of the requirements of the development to convert string into html. Different frameworks have different methods to do this. In Svelte, we use @html tag to let it know that the string has to be parsed as html.

If you display a string with html tags in it, the svelte will not parse it. It will simply show the content as string. But there is a way to get the required results.

Note: You should always filter the html in string to keep it safe. If you do not trust the source, you should not use this functionality. Because there is always a chance of XSS attacks using scripts. But if you are using static html or data from your server, then you may trust it.

Code Example

<script>
 let string = `Tony Stark is <strong>Ironman</strong>`;
</script>

<p>{@html string}</p>

In this code example we are using a text string which has a <strong> tag. If you print it directly, it will show the tags as they are. But using @html, the tag is parsed.

    Tweet this to help others

Live Demo

Open Live Demo