Apparently, this is harder to find than I thought it would be. And it even is so simple...
Is there a function equivalent to PHP's htmlspecialchars built into Javascript? I know it's fairly easy to implement that yourself, but using a built-in function, if available, is just nicer.
For those unfamiliar with PHP, htmlspecialchars translates stuff like <htmltag/>
into <htmltag/>
I know that escape()
and encodeURI()
do not work this way.
Hope this wins the race due to its performance and most important not a chained logic using .replace('&','&').replace('<','<')...
Worth a read: http://bigdingus.com/2007/12/29/html-escaping-in-javascript/
Note: Only run this once. And don't run it on already encoded strings e.g.
&
becomes&amp;
With jQuery it can be like this:
From related question Escaping HTML strings with jQuery
As mentioned in comment double quotes and single quotes are left as-is for this implementation. That means this solution should not be used if you need to make element attribute as a raw html string.
Chances are you don't need such a function. Since your code is already in the browser*, you can access the DOM directly instead of generating and encoding HTML that will have to be decoded backwards by the browser to be actually used.
Use
innerText
property to insert plain text into the DOM safely and much faster than using any of the presented escape functions. Even faster than assigning a static preencoded string toinnerHTML
.Use
classList
to edit classes,dataset
to setdata-
attributes andsetAttribute
for others.All of these will handle escaping for you. More precisely, no escaping is needed and no encoding will be performed underneath**, since you are working around HTML, the textual representation of DOM.
* This answer is not intended for server-side JavaScript users (Node.js, etc.)
** Unless you explicitly convert it to actual HTML afterwards. E.g. by accessing
innerHTML
- this is what happens when you run$('<div/>').text(value).html();
suggested in other answers. So if your final goal is to insert some data into the document, by doing it this way you'll be doing the work twice. Also you can see that in the resulting HTML not everything is encoded, only the minimum that is needed for it to be valid. It is done context-dependently, that's why this jQuery method doesn't encode quotes and therefore should not be used as a general purpose escaper. Quotes escaping is needed when you're constructing HTML as a string with untrusted or quote-containing data at the place of an attribute's value. If you use the DOM API, you don't have to care about escaping at all.There is a problem with your solution code--it will only escape the first occurrence of each special character. For example:
Here is code that works properly:
Update
The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks jbo5112).