与正则表达式替换()上的数组元素(replace() with RegExp on array el

2019-08-16 16:47发布

我想写一个JavaScript函数,一些简单的UBB标签转换像[红] [/红]到HTML的标签。 我想替换()函数来做到这一点的最好办法。 我写了一个简单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>" ,但它只是给了我一个奇怪的字符串。

怎么了? 我觉得这是与我的正则表达式。

Answer 1:

[]正则表达式中具有特殊含义,需要进行转义,而且你不需要正则表达式,你写你的代码,并可以做的方式:

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\]"托架逃脱)。



Answer 2:

只是改变这一行

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

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

去除无用的代码。

replace作品也“正常”(非正则表达式)值作为参数。



Answer 3:

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

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很少使用了,我建议你使用一个span带班。



文章来源: replace() with RegExp on array elements