Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Edward

Php Htmlspecialchars In Javascript

Recommended Posts

What is the best way to do a HtmlSpecialChars in Javascript? I am looking for a clean solution just like that php function equivalent.

Share this post


Link to post
Share on other sites

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('>', '>');
}
 
Thoughts?
  • Upvote 1

Share this post


Link to post
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...

Share this post


Link to post
Share on other sites

I guess the reason i couldn't find your code in JQuery because it must be a part of .createTextNode() as mentioned in the JQuery .text() method.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...