1

I have a string that contains text including special characters like apostrophes, quotes, ampersand etc. that I would like to convert to HTML character codes, e.g. to show &#39 instead of an apostrophe etc. (as per the following list: http://www.w3.org/MarkUp/html-spec/html-spec_13.html.

I do not necessarily need to convert letters and spaces as long as the above and some other basic characters are encoded correctly.

For a temporary workaround I use simple replaces like str = str.replace("'", "&#39") but would like to avoid this as it only covers certain characters.

I was thinking of encodeURI or encodeURIcomponent but would like to know what is the best and easiest way to achieve this without encoding more than necessary.

Can someone tell what is the best way here if the idea is to avoid any issues with other JS where this is inserted dynamically, esp. thinking of single quotes, double quotes and any other character that could cause issues here (referring to JavaScript / jQuery and English language only) ?

Etheryte
  • 24,589
  • 11
  • 71
  • 116
user2571510
  • 11,167
  • 39
  • 92
  • 138
  • I was going to ask this question about a month ago... then forgot. – Piper McCorkle Sep 06 '14 at 17:59
  • 1
    Javascript doesn't really have an entity encoder built in, URI encoding is something completely different. The best option is probably replacement, and that makes this a duplicate. – adeneo Sep 06 '14 at 17:59
  • 1
    see also http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript , it seems beeing a similar article – Aak Sep 06 '14 at 18:04

1 Answers1

1
function encodeEntities(value) {
    return $('<div />').text(value).html();
}
dsuckau
  • 592
  • 3
  • 15