Javascript BBCode Parser recognizes only first list element

拥有回忆 提交于 2020-01-02 08:17:54

问题


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;}

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

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

  • adfasdfdf
  • [*] asdfadsf
    [*] asdfadss

    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?


    回答1:


    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);
    



    回答2:


    try adding the g and m switches /<regex>/gm switches to your regex patterns.



    来源:https://stackoverflow.com/questions/2744423/javascript-bbcode-parser-recognizes-only-first-list-element

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