0

I have a variable that contains html characters. This variable must be converted to an html safe string. How do I do this? Example:

data.X="<img src='abc'>";  
//data.X=magicEncoder(data.X)
//Contents of data.X after magicEncoder:
&lt;img&nbsp;src=&#39;abc&#39;&gt;

I have tried looking up domPurify without success only to have it strip the html instead of encoding the contents.

DKATyler
  • 914
  • 10
  • 16

1 Answers1

1

Have you tried using a library called: he (HTML Entities?

In your example it might look like:

data.X = "<img src='abc'>";
const encodedString = he.encode(data.X);
console.log(encodedString);

which gives you: &lt;img src=&#x27;abc&#x27;&gt;

Let me know how it goes - I haven't used this myself but seems to be a good way to do it. Here's more info from another answer: Whats the right way to decode a string that has special html entities in it

aleksandar
  • 186
  • 12