Jquery 检测 commands/Custom BBcode

Jquery detect commands/Custom BBcode

所以我希望能够检测到我论坛上的用户在 post 中写了什么,并相应地更改它的 CSS。例如,

[hl color:'yellow']example test[/hl]

应该对文本应用突出显示:

style="background-color: yellow"

我希望 jQuery 代码检测 [hl color: 如果成功,将 ' ' 之间的值保存在变量中,然后测试剩余的 ]。然后我希望它将 style="background-color: " + var 应用于 ] 之后和 [/hl]

之前的文本

在此先致谢。

当前无效代码:

$('.post').each(function() {   
  if($(this:contains('[hl color:'))) {
    var txt = [I have no idea];
    $(select the text in between tags).attr('style', 'background-color:' + txt);
  }
});

选项 1:使用库

已经有很多 JavaScript 库解析 BBCode。 This one looks promising, and is extensible so that you can add your own tags. You could also consider doing the parsing on the server side (in PHP or whatever you are using) using a library there (like jBBCode PHP).

选项 2:自己动手

不需要实际的 jQuery。相反,对于简单的标签,正则表达式可以解决问题:

function bbcodeToHTML(bbcode) {
  return bbcode.replace(
           /\[\s*hl\s*color\s*:\s*(.*?)\s*\](.*?)\[\s*\/\s*hl\s*\]/gi,
           '<span style="background-color:;"></span>'
         );
}

那么这个正则表达式有什么作用?

  • \[\s*hl\s*color\s*:\s*:文字 [,然后是任意数量的空格,然后是 color,然后是任意数量的空格,然后是文字 :,然后是任意数量的空格.
  • (.*?):延迟捕获(如 </code>)任何字符。这意味着它会尝试匹配尽可能少的字符。</li> <li><code>\s*\]: 开始标签结束。
  • (.*?):同上,但捕获为</code></li> <li><code>\[\s*\/\s*hl\s*\]: 结束标签,插入任意数量的空格。
  • g:全局标志。替换所有匹配项并且在第一个之后不停止。
  • i:不区分大小写。同时匹配 HLhl.

查看实际效果 here

替换论坛帖子的内容

现在您需要一些 jQuery。我假设包含 BBCode 论坛帖子的元素(您希望用 HTML 替换)都有一个名为 post 的 class,以便可以识别它们。那么这段代码就可以完成工作:

//Itterate over all forum posts.
jQuery('.post').each(function() {

    //Get a reference to the current post.
    currentPost = jQuery(this);

    //Get the content ant turn it into HTML.
    postHTML = bbcodeToHTML(currentPost.html());

    //Put the html into the post.
    currentPost.html(postHTML);

});

有关 jQuery 的更多信息,您可以随时查看 documentation