我有一個字符串,我想轉換爲div,但它並沒有正確關閉div。Javascript BBcode函數不工作
我使用的例子字符串是這樣的:
[quote]Quote by: user1 [quote]Quote by: user2 ads[/quote]Test[/quote]Testing 2.
這導致:
<div class="quote" style="margin-left:10px;margin-top:10px;">
Quote by: user1
[quote]Quote by: user2 ads
</div>
Test[/quote]Testing 2.
但它不會正確地轉換內部引號。
我的JavaScript函數是這樣的:
function bbcode_parser(str) {
search = new Array(
/\[b\](.*?)\[\/b\]/g,
/\[i\](.*?)\[\/i\]/g,
/\[quote](.*?)\[\/quote\]/g,
/\[\*\]\s?(.*?)\n/g);
replace = new Array(
"<strong>$1</strong>",
"<em>$1</em>",
"<div class='quote' style='margin-left:10px;margin-top:10px;'>$1</div>");
for (i = 0; i < search.length; i++) {
str = str.replace(search[i], replace[i]);
}
return str;
}
我提供了一個JSFiddle
給你看它在行動: http://jsfiddle.net/gRaFW/2/
請幫助:)
姆......用正則表達式嵌套。所以這個問題應該叫做nastying。 – acdcjunior
你的正則表達式檢查正確打開和關閉''[quote]'s。它無法正確處理嵌套。老實說,你最好的選擇(使用正則表達式)只是用'
Is there沒有正則表達式更好的選擇? – Sir