jQuery Regex 用于提取除 br、粗体、斜体和 a 之外的所有 HTML

发布于 2024-10-01 16:40:11 字数 766 浏览 1 评论 0原文

我在 jQuery 中使用一个极其丑陋的函数来监听 paste 事件并从粘贴中删除所有无关的 HTML 格式。不幸的是,我现在所拥有的过于严格,而且还很丑陋。

我想改进这个正则表达式,以允许在 WYSIWYG 编辑器中使用相同的 HTML。这意味着我想要
; 允许使用 ; 标签。

我自己不知道足够的正则表达式来执行此操作,并且非常感谢看到这一点的改进。

$('iframe').ready(function() {
  $(this).contents().find('.wysiwyg').find('iframe').contents()
  .find('.wysiwyg').bind('paste', function() {
    var el = $(this);
    setTimeout(function() {
        var strClean = el.text().replace(/<\/?[^>]+>/gi, '');
        el.text(strClean);
    }, 0);
  });
});

您可以在这里看到这个丑陋的代码: http://jsfiddle.net/v4LhV/3/

I'm using an extremely ugly function in jQuery to listen on a paste event and remove all extraneous HTML formatting from the paste. Unfortunately, what I have now is overly strict, on top of just being butt-ugly.

I want to improve this regex to allow for the same HTML I'm already allowing inside the WYSIWYG editor. This means I would like to have <b>, <i>, <br>, and <a> tags allowed.

I do not know enough regex to do this myself, and would be very appreciative to see this improved.

$('iframe').ready(function() {
  $(this).contents().find('.wysiwyg').find('iframe').contents()
  .find('.wysiwyg').bind('paste', function() {
    var el = $(this);
    setTimeout(function() {
        var strClean = el.text().replace(/<\/?[^>]+>/gi, '');
        el.text(strClean);
    }, 0);
  });
});

You can see this ugly code at work here: http://jsfiddle.net/v4LhV/3/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉薄对峙 2024-10-08 16:40:12

由于您手头有一个功能齐全的 DOM 解析器(即浏览器),为什么不使用 .html() 到一个元素(屏幕外),然后使用 .unwrap()

As you have a fully functional DOM parser, namely the browser, at hand, why not just parse the whole thing using .html() in to an element (off screen), then run through removing stuff you do not want using .unwrap().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文