仅识别第一个列表元素

仅识别第一个列表元素

本文介绍了Javascript BBCode Parser 仅识别第一个列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 Javascript BBCode Parser 用于客户端实时预览(不想为此使用 Ajax).问题是,这个解析器只识别第一个列表元素:

I have a really simple Javascript BBCode Parser for client-side live preview (don't want to use Ajax for that). The problem ist, this parser only recognizes the first list element:

function bbcode_parser(str) {
search = new Array(
      /\[b\](.*?)\[\/b\]/,
      /\[i\](.*?)\[\/i\]/,
      /\[img\](.*?)\[\/img\]/,
      /\[url\="?(.*?)"?\](.*?)\[\/url\]/,
      /\[quote](.*?)\[\/quote\]/,
      /\[list\=(.*?)\](.*?)\[\/list\]/i,
      /\[list\]([\s\S]*?)\[\/list\]/i,
      /\[\*\]\s?(.*?)\n/);

replace = new Array(
      "<strong>$1</strong>",
      "<em>$1</em>",
      "<img src=\"$1\" alt=\"An image\">",
      "<a href=\"$1\">$2</a>",
      "<blockquote>$1</blockquote>",
      "<ol>$2</ol>",
      "<ul>$1</ul>",
      "<li>$1</li>");

for (i = 0; i < search.length; i++) {
    str = str.replace(search[i], replace[i]);
}

return str;}

[列表]
[*] adfasdfdf
[*] asdfadsf
[*] asdfadss
[/列表]

[list]
[*] adfasdfdf
[*] asdfadsf
[*] asdfadss
[/list]

只有第一个元素被转换为 HTML List 元素,其余元素保持为 BBCode:

only the first element is converted to a HTML List element, the rest stays as BBCode:

  • adfasdfdf
  • [*] asdfadsf
    [*] asdadss

  • adfasdfdf
  • [*] asdfadsf
    [*] asdfadss

    我尝试使用 "\s"、"\S" 和 "\n",但我主要习惯于 PHP 正则表达式,对 Javascript 正则表达式完全陌生.有什么建议吗?

    I tried playing around with "\s", "\S" and "\n" but I'm mostly used to PHP Regex and totally new to Javascript Regex. Any suggestions?

    推荐答案

    对于多个匹配项,您需要使用带有 g 修饰符的正则表达式:

    For multiple matches you will need to use a regular expression with the g modifier:

      /\[b\](.*?)\[\/b\]/g,
      /\[i\](.*?)\[\/i\]/g,
      /\[img\](.*?)\[\/img\]/g,
      /\[url\="?(.*?)"?\](.*?)\[\/url\]/g,
      /\[quote](.*?)\[\/quote\]/g,
      /\[list\=(.*?)\](.*?)\[\/list\]/gi,
      /\[list\]([\s\S]*?)\[\/list\]/gi,
      /\[\*\]\s?(.*?)\n/g);
    

    这篇关于Javascript BBCode Parser 仅识别第一个列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-01 00:27