The most commonly used way is using jQuery for this purpose:
var safestring = $('<div>').text(unsafestring).html();
If you want to to encode all the HTML entities you will have to use a library or write it yourself.
You can use a more compact library than jQuery, like HTML Encoder and Decode