Skip to content Skip to sidebar Skip to footer

Replace() With Regexp On Array Elements

I want to write a JavaScript function which converts some simple BBcode Tags like [red] [/red] to Html-Tags. I think the replace() function is the best way to do it. I wrote a simp

Solution 1:

[ and ] have special meaning in regular expressions and need to be escaped, moreover you do not need regular expressions the way you've written your code and can just do:

functionbbToHtml(form) {
    debuggervar text = form.text.value;
    bbTags = newArray("[red]", "[yellow]", "[green]", "[/red]", "[/yellow]", "[/green]");
    htmlTags = newArray("<font color='red'>", "<font color='yellow'>", "<font color='green'>", "</font>", "<font>", "</font>");

    for (var i = 0; i < bbTags.length; i++) {
        while(text.indexOf(bbTags[i])!==-1){
            text = text.replace(bbTags[i], htmlTags[i]);
        }
    }

    alert(text);
}

Just to let you know, you can use array literals so instead of arrays. new Array(comma seperated values) is identical to [comma seperated values] in javascript. Also, you can use your array like a map in your case, for example:

var bbTagsToHTML = {}
bbTagsToHtml["[red]"] = "<font color='red'>"

and iterate through that.

If you would like you can escape your regular expressions too, please see How do you use a variable in a regular expression? for a function that does that.

You can also do that manually. "[red]" becomes "\[red\]" (the bracket escaped).

Solution 2:

just change this line

text = text.replace(re, htmlTags[i]);

into

text = text.replace(bbTags[i], htmlTags[i]);

removing unuseful code.

replace works also on 'normal' (not regex) values as argument.

Solution 3:

If you want to do it with regex you can simplify a lot. No arrays or loops:

var str = '[red]foo[/red] hello world [blue]hey[/blue]',
    re = /\[(\w+)\](.*)\[\/\1\]/g;

str = str.replace(re, '<fontcolor="$1">$2</font>');

console.log(str);
//^ <fontcolor="red">foo</font> hello world <fontcolor="blue">hey</font>

Also, as a side note, font is rarely used anymore I'd suggest you use a span with a class.

Post a Comment for "Replace() With Regexp On Array Elements"