Reputation: 281
This
[b]this text is bold[/b]
[i]this text is [b]italic[/b][/i]
parse out to this (in html)
<b>this text is bold[/b]<br><i>this text is [b]italic</i></b>
this text is bold[/b]
this text is [b]italic
using this function
function bbcode(input){
return input
.replace(/\[b\]([^]*)\[\/b\]/ig, '<b>$1</b>')
.replace(/\[i\]([^]*)\[\/i\]/ig, '<i>$1</i>');
}
I figure there has to be a problem with the regular expression finding each set of tags, but it appears that only the first bold tag and the last bold end tag are being parsed. Any idea how this can be fixed?
Upvotes: 0
Views: 164
Reputation: 15106
function bbcode(input){
var b = /\[b\]([^[]*(?:\[(?!b\]|\/b\])[^[]*)*)\[\/b\]/ig;
var i = /\[i\]([^[]*(?:\[(?!i\]|\/i\])[^[]*)*)\[\/i\]/ig;
while (input.search(b) !== -1) {
input = input.replace(b,'<b>$1</b>');
}
while (input.search(i) !== -1) {
input = input.replace(i,'<i>$1</i>');
}
return input.replace(/\n/ig, '<br>');
}
BBCode:
[b]x[b]y[/b]z[/b]
[b]this text is bold[/b]
[i]this text is [b]italic[/b][/i]
Usage:
var string = '[b]x[b]y[/b]z[/b]\n[b]this text is bold[/b]\n[i]this text is [b]italic[/b][/i]';
console.log(bbcode(string));
Output:
<b>x<b>y</b>z</b><br><b>this text is bold</b><br><i>this text is <b>italic</b></i>
See DEMO.
Upvotes: 1