JavaScript - 替换/正则表达式在论坛中格式化引号

时间:2014-11-07 17:14:55

标签: javascript regex replace

var quote = '[[quote=bob]This is some text bob wrote[/quote]]';

我正在尝试替换/正则表达式,所以它看起来像:

<div class="quote">
     <div class="author>bob</div>
     <div class="text">This is some text bob wrote</div>
</div>

我试图解决这个问题:'/\[quote=(.*?)](.*?)\[\/quote]/'但我对正则表达式并不满意。

2 个答案:

答案 0 :(得分:0)

经过几个小步骤,我设法把它放在一起:

var t = 'some text here [[quote=bob]This is some text bob wrote[/quote]] other text here. Some other text here [[quote=joe]This is some text joe wrote[/quote]] other text here';
var rgx1 = (/(\[\[quote=.*?\].*?\[\/quote\]\])/);
var a = t.split(rgx1);

for(var i = 0; i < a.length; i++){
    var rgx2 = (/\[\[quote=(.*?)](.*?)\[\/quote]\]/);
    if(a[i].match(rgx2) !== null){
        var b = a[i].split(rgx2);

        for(var j = b.length -1; j >= 0; j--){
            if(b[j].length === 0){
                b.splice(j, 1);
            }
        }

        a[i] = '<div class="quote"><div class="author">' + b[0] + '</div><div class="text">' + b[1] + '</div></div>';
    }
}

console.log(a.join(''));

答案 1 :(得分:0)

使用捕获:

quote = quote.replace(/\[\[quote=([^\]]+)\]([^[]+)\[\/[^\]]+\]\]/g, "\n<div class='quote'>\n  <div class='author'>$1</div>\n  <div class='text'>$2</div>\n</div>\n");
相关问题