Saturday, April 12, 2008

Escaping HTML the easy way

If you've done even a little bit of web development, you've probably had to write some sort of html-escaping script before to avoid html injection scenarios (when outputting user-generated content to a page, most likely). It probably looks something like the following (in javascript):

//the old-school way
var escapeHTML = function(s) {
  s = s.replace(/&/g,"&");
  s = s.replace(/</g,"&lt;");
  s = s.replace(/>/g,"&gt;");
  return s;

Seems kinda clunky, doesn't it?

Here's a much simpler way to do it:

var escapeHTML = function(s) {
  return "<![CDATA[" + s + "]]>"

No comments:

Post a Comment