将嵌套 html 转换为 bbCode 引用标签

2024-04-02

我正在尝试转换以下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>

到以下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 = $('<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 http://jsfiddle.net/tE77x/3/

限制:

  1. 它不会将其他 HTML 转换为 BBCode (<b>, <i>、锚标签等);
  2. 缩进/空白不是 100% 准确。

我将使用 Ajax 从数据库获取实际的帖子内容或使用适当的 jQuery bbCode 解析库。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将嵌套 html 转换为 bbCode 引用标签 的相关文章

随机推荐