Simple HTML sanitizer in Javascript

China☆狼群 提交于 2019-11-27 20:05:09
Michael Dillon

You should have a look at the one recommended in this question Sanitize/Rewrite HTML on the Client Side

And just to be sure that you don't need to do more about XSS, please review the answers to this one How to prevent Javascript injection attacks within user-generated HTML

We've developed a simple HtmlSantizer and opensourced it here: https://github.com/jitbit/HtmlSanitizer

Usage

var result = HtmlSanitizer.SanitizeHtml(input);

[Disclaimer! I'm one of the authors!]

for my function I've only cared that the string is not empty and contains only alphanumeric characters. This uses plain JS and no third libraries or anything. It contains a long regex, but it does the job ;) You could build on this but have your regex be something more alike '< script >|< /script >' (with characters escaped where necessary, and minus the spaces). ;)

    var validateString = function(string) {

      var validity = true;

      if( string == '' ) { validity = false; }

      if( string.match( /[ |<|,|>|\.|\?|\/|:|;|"|'|{|\[|}|\]|\||\\|~|`|!|@|#|\$|%|\^|&|\*|\(|\)|_|\-|\+|=]+/ ) != null ) {

          validity = false;
      }

      return validity;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!