Converting nested html to bbCode quote tags

孤街浪徒 提交于 2019-12-24 00:44:30

问题


I am trying to convert the following html

<div class="bbQuote">
    <div class="quoteAuthor">Joe Block</div>
    <div class="quoteContent">This is the first message<br>
        <div class="bbQuote">
            <div class="quoteAuthor">Jane Doe</div>
            <div class="quoteContent">This is the second message</div>
        </div>
    </div>
</div>

to the following bbCode

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

How can I do this using jQuery?

PS: Nested HTML can have zero or more children


回答1:


Here's a very basic example:

var html = $('#commentContent').html(),
    beingParsed = $('<div>' + html.replace(/<br>/g, '\n\r') + '</div>'),
    $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();

Fiddle

Limitations:

  1. It won't convert other HTML to BBCode (<b>, <i>, anchor tags etc);
  2. Indentation/white space is not 100% accurate.

I'd use Ajax to fetch the actual post content from the DB or use a proper jQuery bbCode parsing library.



来源:https://stackoverflow.com/questions/12519688/converting-nested-html-to-bbcode-quote-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!