最新消息:

JS去除html标签

html admin 3618浏览 0评论

网上虽然流传了许多js去除html标签的版本,但是很多都是互相抄袭,且会错误的过滤这样的不是html标签的字符.
贴出本人写的一个真正能够正确过滤html标签的方法,
使用方法:

"<a>测试过滤</a><br><p>".filterHtmlTag("a", "br")
  • 函数参数即忽略过滤的html标签名

过滤函数

String.prototype.filterHtmlTag = function(){
    var tagsArr     = ["!DOCTYPE","a","abbr","address","applet","acronym","area","article","aside","audio","b","base","basefont","bdi","bdo","big","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","command","datalist","dd","del","details","dfn","dir","div","dl","dt","em","embed","fieldset","figcaption","figure","font","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","keygen","kbd","label","legend","li","link","map","mark","menu","meta","meter","nav","noframes","noscript","object","ol","optgroup","option","output","p","param","pre","progress","q","rp","ruby","s","samp","script","select","small","source","span","strike","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","tt","u","ul","var","video","wbr","rt","section","isindex"],
       tags     = "",
       tagsReg;
    if( arguments.length > 0 ){
       for(var i=0;i<arguments.length;i++){
      var ingIndex = tagsArr.indexOf(arguments[i]);
      if(-1 != ingIndex){
           tagsArr.splice(ingIndex, 1);
      }
       }
    }
    tags            = tagsArr.join("|");
    tagsReg     = new RegExp("(?=<[/]?("+ tags +"){1}?(>|[s]+))[^>]+?>", "g");
    return this.replace(tagsReg, "");
 }

转载请注明:爱开源 » JS去除html标签

您必须 登录 才能发表评论!