How to convert characters to HTML entities using plain JavaScript

Viewed 120012

I have the following:

var text = "Übergroße Äpfel mit Würmern";

I'm searching for a Javascript function to transform the text so that every special letter is represented by its HTML entity sequence like this:

var newText = magicFunction(text);
...
newText = "Übergroße Äpfel mit Würmern";

The function should not only escape the letters of this example but also all of these.

How would you achieve that? Is there any existing function out there? (Plain, because a solution without a framework is preferred)

Btw: Yes, I've seen this question but it doesn't address my need.

12 Answers

I recommend to use the JS library entities. Using the library is quite simple. See the examples from docs:

const entities = require("entities");
//encoding
entities.escape("&"); // "&"
entities.encodeXML("&"); // "&"
entities.encodeHTML("&"); // "&"
//decoding
entities.decodeXML("asdf & ÿ ü '"); // "asdf & ÿ ü '"
entities.decodeHTML("asdf & ÿ ü '"); // "asdf & ÿ ü '"
Related