htmlspecialchars function for Javascript / jQuery

I was dealing with user input on a web form using a little AJAX magic to auto-update the database while keeping the user on the same page.  I always use the PHP function htmlspecialchars to clean up text input, and needed something similar for my javascript code.  I couldn’t find anything* so I wrote my own.  Maybe this will come in handy for someone else.

According to the htmlspecialchars function page on, the translations performed are:-

‘&’ (ampersand) becomes ‘&’
‘”‘ (double quote) becomes ‘"’
“‘” (single quote) becomes ‘'’
‘<‘ (less than) becomes ‘&lt;’
‘>’ (greater than) becomes ‘&gt;’

So here’s my function for javascript written using the .replace method:-

Take note, we need to use the ‘g’ to globally match, or the above function will only replace the first instance of each character.

* if this function already exists in the jQuery library, please let me know in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *