Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 318
leora Avatar asked Sep 03 '25 03:09

leora


1 Answers

No but you can write one pretty easily.

function htmlEnc(s) {
  return s.replace(/&/g, '&amp;')
    .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.

like image 93
Pointy Avatar answered Sep 04 '25 18:09

Pointy