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?

有帮助吗?

解决方案

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

}
...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top