0

我想编写一个 JavaScript 函数,将一些简单的 BBcode 标签(如 [red] [/red])转换为 Html-Tags。我认为 replace() 函数是最好的方法。我写了一个简单的 testfunction 来尝试一下,但它似乎不起作用。

/**
* @function
* @description Replaces the bb-tags with html-tags
*/
function bbToHtml(form) {
    debugger

    var text = form.text.value;
    bbTags = new Array("[red]", "[yellow]", "[green]", "[/red]", "[/yellow]", "[/green]");
    htmlTags = new Array("<font color='red'>", "<font color='yellow'>", "<font color='green'>", "</font>", "<font>", "</font>");

    for (var i = 0; i < bbTags.length; i++) {
        var re = new RegExp(bbTags[i], "g");
        text = text.replace(re, htmlTags[i]);
    }

    alert(text);
}

它应该转换"[red]hello[/red]""<font color='red'>hello</font>",但它只是给了我一个奇怪的字符串。

怎么了?我认为这与我的正则表达式有关。

4

3 回答 3

2

[并且]在正则表达式中具有特殊含义并且需要转义,而且您不需要像编写代码那样的正则表达式并且可以这样做:

function bbToHtml(form) {
    debugger

    var text = form.text.value;
    bbTags = new Array("[red]", "[yellow]", "[green]", "[/red]", "[/yellow]", "[/green]");
    htmlTags = new Array("<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);
}

只是让您知道,您可以使用数组文字而不是数组。new Array(comma seperated values)[comma seperated values]javascript中的相同。此外,在您的情况下,您可以像使用地图一样使用数组,例如:

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

并遍历它。

如果您希望也可以转义正则表达式,请参阅如何在正则表达式中使用变量?对于执行此操作的功能。

您也可以手动执行此操作。"[red]"变成"\[red\]"(括号转义)。

于 2013-01-31T22:32:23.100 回答
0

只需更改此行

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

进入

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

删除无用的代码。

replace也适用于“正常”(不是正则表达式)值作为参数。

于 2013-01-31T22:34:34.317 回答
0

如果你想用正则表达式来做,你可以简化很多。没有数组或循环:

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

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

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

另外,作为旁注,font很少使用了,我建议您将 aspan与类一起使用。

于 2013-01-31T22:41:02.463 回答