从传入HTML字符串中删除所有标签
$(function() { var htmlPrefilter = $.htmlPrefilter, rdel = /<(del)(?=[\s>])[\w\W]*?<\/\1\s*>/gi; $.htmlPrefilter = function( html ) { return htmlPrefilter.call( this, html ).replace( rdel, "" ); }; var htm = '<del>删除</del><h1>标题</h2>'; $('body').append($.htmlPrefilter(htm)); });
$.htmlPrefilter() 函数通过jQuery操作方法修改和过滤HTML字符串。
注意:1. 这种方法很少需要直接调用,反而可以使用这个方法作为修改现有jQuery操作方法的一个切入点。
参数 | 描述 |
---|---|
html | String类型 在该HTML字符串上进行操作 |
确保任何HTML字符串都符合XHTML标准
$(function() { var panything = "[\\w\\W]*?", // 空白 pspace = "[\\x20\\t\\r\\n\\f]", // 标签结尾(whitespace or greater-than) pnameEnd = pspace.replace( "]", ">]" ), // 标签名 // https://html.spec.whatwg.org/multipage/syntax.html#tag-open-state // https://html.spec.whatwg.org/multipage/syntax.html#tag-name-state pname = "[a-z]" + pnameEnd.replace( "[", "[^/\\0" ) + "*", // 空元素 // https://html.spec.whatwg.org/multipage/syntax.html#void-elements pvoidName = "(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|" + "source|track|wbr)(?=" + pnameEnd + ")", // 属性 // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 pattrs = "(?:" + pspace + "+[^\\0-\\x20\\x7f-\\x9f=\"'/>]+(?:" + pspace + "*=" + pspace + "*(?:\"" + panything + "\"|'" + panything + "'|" + pnameEnd.replace( "[", "[^" ) + "*(?!/)" + ")|))*" + pspace + "*", // 关闭标签的尾随内容 pcloseTail = "(?:" + pspace + panything + "|)", rspecialHtml = new RegExp( // 自关闭的非空元素: $1–$5 "(<)(?!" + pvoidName + ")(" + pname + ")(" + pattrs + ")(\\/)(>)|" + // 非 HTML容器 (element, comment, 或者 CDATA): $6 "(<(script|style|textarea)" + pattrs + ">" + panything + "<\\/\\7" + pcloseTail + ">|" + "<!--" + panything + "--)", "gi" ), pspecialReplacement = "$1$2$3$5$1$4$2$5$6"; $.htmlPrefilter = function( html ) { return ( html + "" ).replace( rspecialHtml, pspecialReplacement ); }; var htm = '<a /><meta>1516</meta>'; alert($.htmlPrefilter(htm)); alert(htm); });
任何HTML字符串都符合XHTML标准,从传入HTML字符串中删除所有 <del>标签也可以这样解决。