Edward Posted January 9, 2014 Share Posted January 9, 2014 What is the best way to do a HtmlSpecialChars in Javascript? I am looking for a clean solution just like that php function equivalent. Link to comment Share on other sites More sharing options...
HartleySan Posted January 9, 2014 Share Posted January 9, 2014 According to the PHP.net page for htmlspecialchars, htmlspecialchars performs the following conversions: '&' (ampersand) becomes '&' '"' (double quote) becomes '"' when ENT_NOQUOTES is not set. "'" (single quote) becomes ''' (or ') only when ENT_QUOTES is set. '<' (less than) becomes '<' '>' (greater than) becomes '>' So the following JS should suffice: function htmlspecialchars(str) { return str.replace('&', '&').replace('"', '"').replace("'", ''').replace('<', '<').replace('>', '>'); } Thoughts? 1 Link to comment Share on other sites More sharing options...
Edward Posted January 10, 2014 Author Share Posted January 10, 2014 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 More sharing options...
HartleySan Posted January 10, 2014 Share Posted January 10, 2014 Well, whatever works, go with it. Thanks for doing the research. Link to comment Share on other sites More sharing options...
Edward Posted January 13, 2014 Author Share Posted January 13, 2014 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. Link to comment Share on other sites More sharing options...
HartleySan Posted January 13, 2014 Share Posted January 13, 2014 My code is probably not in the jQuery codebase. I wrote that code myself. Link to comment Share on other sites More sharing options...
Recommended Posts