【问题标题】:JavaScript - replace / regex for formatting quotes in a forumJavaScript - 替换/正则表达式以格式化论坛中的引号
【发布时间】:2014-11-07 17:14:54
【问题描述】:
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]/',但我不擅长正则表达式。
【问题讨论】:
标签:
javascript
regex
replace
【解决方案1】:
经过几个小步骤,我设法把它放在一起:
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(''));
【解决方案2】:
使用捕获:
quote = quote.replace(/\[\[quote=([^\]]+)\]([^[]+)\[\/[^\]]+\]\]/g, "\n<div class='quote'>\n <div class='author'>$1</div>\n <div class='text'>$2</div>\n</div>\n");