用数组元素上的RegExp替换() [英] replace() with RegExp on array elements

查看:124
本文介绍了用数组元素上的RegExp替换()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 simple testfunction to try it, but it does not seem to work.

/**
* @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 [/红色]< font color ='red'> hello< / font>,但它只是给了我一个奇怪的字符串。

It should convert "[red]hello[/red]" to "<font color='red'>hello</font>", but it just gives me a weird string.

有什么问题?我认为这与我的正则表达式有关。

What is wrong? I think this has something to do with my regular expression.

推荐答案

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

[ 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:

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

为了让您知道,您可以使用数组文字而不是数组。 新数组(逗号分隔值)与javascript中的 [逗号分隔值] 相同。
另外,你可以像你的情况一样使用你的数组,例如:

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'>"

并迭代完毕。

如果你希望你也可以逃避正则表达式,请参阅如何在正则表达式中使用变量?用于执行此操作的函数。

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.

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

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

这篇关于用数组元素上的RegExp替换()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆