0

I am trying to make a makeshift BBCode parser for fun and I have it to where it will replace all tags that are not the same but I cannot get it to replace two or more of the same tags in a row. For example I have the following BB:

[big][big][c red]WARNING[/c][/big][/big]

it will only output:

<span style="font-size: larger;">[big]<span style="color: red">WARNING</span></span>[/big]

the code I am using is as follows:

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); 
}

Is there anyway I can make this replace nested elements as well?

asked Apr 8, 2014 at 21:58

1 Answer 1

0

There's probably a much cleaner solution, but this will fix your problem. Basically, keep replacing until the regex can't find a match. It's not a full-proof solution, but will work on correctly formatted BBCode

...
for (var i = 0; i < find.length; i++) {
 while(find[i].test(text)) {
 text = text.replace(find[i], replace[i]);
 }
}
...
answered Apr 8, 2014 at 22:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.