Jump to content
Larry Ullman's Book Forums

Php Htmlspecialchars In Javascript

Recommended Posts

According to the PHP.net page for htmlspecialchars, htmlspecialchars performs the following conversions:

  1. '&' (ampersand) becomes '&'
  2. '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
  3. "'" (single quote) becomes ''' (or ') only when ENT_QUOTES is set.
  4. '<' (less than) becomes '<'
  5. '>' (greater than) becomes '>'
So the following JS should suffice:
function htmlspecialchars(str) {
  return str.replace('&', '&').replace('"', '"').replace("'", ''').replace('<', '<').replace('>', '>');
  • Upvote 1
Link to comment
Share on other sites

I really like your answer, however i realize now i have gotten myself into a muddle. I have a server PHP function that retrieves members questions specific to there ID. It did occur to me that i would need to use something along the lines of your function. However now i realize i don't need it as the JQuery .text() method will already do this for me.


$('#question').text(data);     // http://api.jquery.com/text/


"We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML. Consider the following HTML:"


I just had a go at trying to find stuff similar to your function in the jquery script but couldn't find anything http://code.jquery.com/jquery-2.0.2.js


Thanks for your Help...

Link to comment
Share on other sites


  • Create New...