将嵌套的html转换为bbCode引用标记

我试图转换以下的HTML

Joe Block
This is the first message
Jane Doe
This is the second message

到以下bbCode

 [quote=Joe Block] This is the first message [quote=Jane Doe] This is the second message [/quote] [/quote] 

我怎么能用jQuery做到这一点?

PS:嵌套HTML可以有零个或多个子项

这是一个非常基本的例子:

 var html = $('#commentContent').html(), beingParsed = $('
' + html.replace(/
/g, '\n\r') + '
'), $quote; while (($quote = beingParsed.find('.bbQuote:first')).length) { var $author = $quote.find('.quoteAuthor:first'), $content = $quote.find('.quoteContent:first'), toIndent = $author[0].previousSibling; toIndent.textContent = toIndent.textContent.substring(0, toIndent.textContent.length-4); $author.replaceWith('[quote=' + $author.text() + ']'); $content.replaceWith($content.html()); $quote.replaceWith($quote.html() + '[/quote]'); } var parsedData = beingParsed.html();

小提琴

限制:

  1. 它不会将其他HTML转换为BBCode( ,锚标签等);
  2. 压痕/空白不是100%准确。

我将使用Ajax从数据库中获取实际的post内容或使用正确的jQuery bbCode解析库。