Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode?

c#, html-encode, javascript

Solution

No but you can write one pretty easily.

function htmlEnc(s) {
  return s.replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/'/g, '&#39;')
    .replace(/"/g, '&#34;');
}

I've played with ways of making that faster (basically to do things with one "replace" call) but this performs well enough for most purposes, especially in modern browsers.

Problem

Possible Duplicate: JavaScript/jQuery HTML Encoding I am passing info down to the client as Json and I am generating some HTML from my javascript code. I have a field called name which I pass into the title of an image like this: ``` html.push("<img title='" + person.Name + "' src . . . ``` the issue is if the person.Name is "Joe O'Mally' as it only shows up as "Joe O" when i hover over the image (because of the ' in the name) I don't want to strip the ' on the serverside as there are other places where I want to show the exact string on the page. Is there an Equivalent of HttpUtility.HtmlEncode in javascript that will show the full name in the image title, when I hover of the image?

Original source

Related problems