Javascript BBCode 解析器仅识别第一个列表元素
我有一个非常简单的 Javascript BBCode 解析器,用于客户端实时预览(不想使用 Ajax)。问题是,这个解析器只识别第一个列表元素:
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]
只有第一个元素被转换为 HTML List 元素,其余元素保持为 BBCode:
[*] asdfadss
我尝试使用“\s”、“\S”和“\n”,但我主要习惯 PHP 正则表达式,而对 Javascript 正则表达式完全陌生。有什么建议吗?
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:
[*] 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于多个匹配,您需要使用带有
g
修饰符的正则表达式:For multiple matches you will need to use a regular expression with the
g
modifier:尝试将 g 和 m 开关
//gm
开关添加到您的正则表达式模式中。try adding the g and m switches
/<regex>/gm
switches to your regex patterns.