jQuery - 如何格式化HTML内容以删除标签,但插入\ n

时间:2013-10-17 02:06:46

标签: jquery regex formatting tinymce

我正在尝试在jQuery中格式化HTML内容以发布到Facebook事件。

基本上我想采取一些内容,如:

<p>Plus&nbsp;<a id=\"js_131\" href=\"https://www.facebook.com/themotorleague?directed_target_id=0\" data-hovercard=\"/ajax/hovercard/page.php?id=42475533139&amp;extragetparams=%7B%22directed_target_id%22%3A0%7D\" data-mce-href=\"https://www.facebook.com/themotorleague?directed_target_id=0\">The Motorleague</a></p>
<p><a href=\"https://www.facebook.com/AtomiqueProductions/events?directed_target_id=0\" data-hovercard=\"/ajax/hovercard/page.php?id=133649633385384&amp;extragetparams=%7B%22directed_target_id%22%3A0%7D\" data-mce-href=\"https://www.facebook.com/AtomiqueProductions/events?directed_target_id=0\">Atomique Productions</a>&nbsp;and&nbsp;<a href=\"https://www.facebook.com/thezone.fm?directed_target_id=0\" data-hovercard=\"/ajax/hovercard/page.php?id=339763011997&amp;extragetparams=%7B%22directed_target_id%22%3A0%7D\" data-mce-href=\"https://www.facebook.com/thezone.fm?directed_target_id=0\">The Zone @ 91-3, Modern Rock in Victoria</a>&nbsp;present</p>
<p>-&nbsp;<a href=\"https://www.facebook.com/TheBalconies?directed_target_id=0\" data-hovercard=\"/ajax/hovercard/page.php?id=7677069042&amp;extragetparams=%7B%22directed_target_id%22%3A0%7D\" data-mce-href=\"https://www.facebook.com/TheBalconies?directed_target_id=0\">THE BALCONIES</a>&nbsp;-</p>

并通过jQuery函数传递它以删除所有HTML标记,只要<p>存在,添加\n\r\使其看起来像:

  

加上Motorleague

     

Atomique Productions和The Zone @ 91-3,Victoria Rock in Victoria   本

     

- BALCONIES -

这可能吗?

如果相关,HTML内容将直接来自WordPress帖子页面的TinyMCE编辑器。

1 个答案:

答案 0 :(得分:1)

这就是你的意思:

var $el = jQuery('p');

console.log(doit($el));

function doit($el)
{
  var ret = '';
  $el.each(function()
  {
      ret += jQuery(this).text() + '\n\r';
  })
  return ret;
}

输出:

Plus The Motorleague
Atomique Productions and The Zone @ 91-3, Modern Rock in Victoria present
- THE BALCONIES -

REVISIED:

var $el = jQuery('<div>' + str + '</div>').find('*');

console.log(doit($el));

function doit($el)
{
  var ret = '';
  $el.each(function()
  {
      var nl = $(this).is('p') ? '\n\r' : '';
      ret += jQuery(this).text() + nl;
  });
  return ret;
}