我正在尝试制作一个临时的BBCode解析器以获得乐趣,我将它用于替换所有不同的标签,但我不能让它替换连续的两个或多个相同的标签。例如,我有以下BB:
[big][big][c red]WARNING[/c][/big][/big]
它只会输出:
<span style="font-size: larger;">[big]<span style="color: red">WARNING</span></span>[/big]
我使用的代码如下:
function parseBBCode(text, element) {
//RegExp for BBCode to find
var find = new Array();
find[0] = /\[b\](.*?)\[\/b\]/g; //Bold
find[1] = /\[bg (.*?)\](.*?)\[\/bg\]/g; //Background
find[2] = /\[big\](.*?)\[\/big\]/g; //Big
find[3] = /\[c (.*?)\](.*?)\[\/c\]/g; //Color
find[4] = /\[f (.*?)\](.*?)\[\/f\]/g; //Font
find[5] = /\[i\](.*?)\[\/i\]/g; //Italics
find[6] = /\[img (.*?)\]/g; //Image
find[7] = /\[p\](.*?)\[\/p\]/g; //Pre
find[8] = /\[small\](.*?)\[\/small\]/g; //Small
find[9] = /\[s\](.*?)\[\/s\]/g; //Strike
var replace = new Array();
replace[0] = "<span style=\"font-weight: bold;\">$1</span>";
replace[1] = "<span style\"background-color: $1\">$2</span>";
replace[2] = "<span style=\"font-size: larger;\">$1</span>";
replace[3] = "<span style=\"color: $1\">$2</span>";
replace[4] = "<span style=\"font-family: $1\">$2</span>";
replace[5] = "<span style=\"font-style: italic;\">$1</span>";
replace[6] = "<a href=\"$1\"><img src=\"$1\" style=\"max-height: 200px; max-width: 200px;\" /></a>";
replace[7] = "<pre>$1</pre>";
replace[8] = "<small>$1</small>";
replace[9] = "<span style=\"text-decoration: line-through;\">$1</span>";
for (var i = 0; i < find.length; i++) {
text = text.replace(find[i], replace[i]);
}
$(element).html(text);
}
无论如何我还可以替换嵌套元素吗?
答案 0 :(得分:0)
可能有一个更清洁的解决方案,但这将解决您的问题。基本上,继续替换,直到正则表达式找不到匹配项。它不是一个完整的解决方案,但可以使用正确格式化的BBCode
...
for (var i = 0; i < find.length; i++) {
while(find[i].test(text)) {
text = text.replace(find[i], replace[i]);
}
}
...