By using the browsers DOM you can let the browser do the work for you. Make a HTML node, append a text node to it and put in the text node the html code you wish to escape. Only for double quotes you might need to account by doing a replace on them to " and single quotes to 'If you'll just paste 3-byte characters of some encoding right into your HTML code, without " escaping " them (e.g. converting them to their symbol entity codes), you might get into big trouble. This is because HTML code should be written and read in ASCII encoding.
How to escape HTML characters?
How to Escape HTML Characters. 1 Replace < with <. 2 Replace > with > Example: <p> You should only use one <code>< h1 ></code> element per article. </p> Now the code above will render correctly:
Do you need special characters in HTML?
The code also contains normal text characters such as those in headlines and paragraphs designed for the viewer to read. When you use HTML and type the text designed to be viewed, you usually don't need any special codes β you use just your computer keyboard to add the appropriate letters or characters.
Can I just paste 3-byte characters in HTML code without escaping?
If you'll just paste 3-byte characters of some encoding right into your HTML code, without " escaping " them (e.g. converting them to their symbol entity codes), you might get into big trouble. This is because HTML code should be written and read in ASCII encoding.
Why can't I escape special characters in a URL?
This is because all other escaped characters start with " & ". And so if you'll write the path to your php file, or whatever like this: " //example.com/?a=1&b=2 ", your browser may think, that by " &b " you wanted to express some non-ASCII character. This is why you should try to "escape" special characters in URL's.

Below are two helpful articles on a similar topic π
What is the use of htmlspecialchars() function?How to escape special characters in HTML and JavaScript?