htmlEntities for JavaScript
htmlentities() is a PHP function which converts special characters (like <) into their escaped/encoded values (like <). This allows you to show to display the string without the browser reading it as HTML.
JavaScript doesn't have a native version of it. If you just need the very basics to so that the browser won't interpret as HTML, this should work fine (via James Padolsey and I got a a similar idea from David Walsh).
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
The PHP.js project, which is a project to port over all of PHP's native functions to JavaScript, contains an example as well. I tried it and it works, but I've been warned much of the code from that project is poorly written, so I've kept it simple and used the above.
I use the following two functions, in my opinion a very solid, complete and easy method.
This particulary example uses jQuery but the principe isn’t dependant on jQuery:
Can you show an example of the above jquery encoding working on a form?
Is this right?
Thanks a lot haha! It’ll solve a lot of problems with AJAX for me :D
Sure, here you go:
http://krinkle-tools.grizzdesign.nl/js-htmlentities.html
Thanks for the two functions, that helped me out of a pickle working with a serialized query string.
Thanks for the info!! (^_^)b
the problem with the jQuery approach is if your text contains htmlentities, e.g.
$(”).text(‘&’).html()
outputs:
“&”
maybe not what you want…..
entities filtered in above post. should read:
$(‘<p>’).text(‘&’).html()
will output
&amp;
Thanks it helped..:)?
Sure it works when you post, but what about saving
The problem with this approach, as Buzz alluded to, is that all ampersands, even if already properly html-ized, will be matched, resulting in things like
htmlentities("&") == "&amp;"andhtmlentities(htmlentities("<")) == "&lt;"(not that you’d do the latter, but just to illustrate the point). You want to pad the ampersand regex. Just a space will work for most cases, i.e.:or you can get fancier with something along the lines of:
How does one do the opposite of this? I want to show the interpreted html entity in js. Example:
Would like ‘textNext’ to output as Go to step two »
Please note that this doesn’t do the same as the PHP function. The PHP function uses HTML entities; while this function uses XML ones.
For example, this function leaves
Orléansunaltered, while the PHP function turns that string intoOrléans.Helped me a lot… krEncodeEntities, krDencodeEntities solved my problem…