使用HTML中的正则表达式着色文本

时间:2013-07-11 09:29:40

标签: javascript regex

我想使用正则表达式转换以下文本,以便^text^中的文本被某些HTML标记内的文本替换。 (在<font color='red'></font>

示例:

Input Text: Please select ^Continue^ to proceed with your call or ^Exit^ to call

Output Text: Please select <font color='red'>Continue</font> to proceed with your call or <font color='red'>Exit</font> to call

是否可以在javascript中使用正则表达式实现上述目标?

3 个答案:

答案 0 :(得分:2)

your_string.replace(/\^(.*?)\^/g, "<font color='red'>$1</font>");

示例:

> a = "Please select ^Continue^ to proceed with your call or ^Exit^ to call"
"Please select ^Continue^ to proceed with your call or ^Exit^ to call"
> a.replace(/\^(.*?)\^/g, "<font color='red'>$1</font>");
"Please select <font color='red'>Continue</font> to proceed with your call or 
<font color='red'>Exit</font> to call"

答案 1 :(得分:2)

使用yourstring.replace(/\^([^\^]*)\^/g,"<font color='red'>$1</font>")

Explanation  -- Starting ^
               ------- Match everything but ^, in $1
                       -- End with ^

g是全局标志,表示正则表达式将匹配所有匹配。

示例:

text= "Please select ^Continue^ to proceed with your call or ^Exit^ to call"
result=text.replace(/\^([^\^]*)\^/g,"<font color='red'>$1</font>")

答案 2 :(得分:0)

可能更好地制作某种解析功能,取决于你的情况,就像这样。

的Javascript

function wrapMarked(string, open, close) {
    if (typeof string !== "string", typeof open !== "string", typeof close !== "string") {
        throw new TypeError("Arguments must be strings.");
    }

    if ((string.match(/\^/g) || []).length % 2 !== 0) {
        throw new Error("We have unmatched '^'s.");
    }

    string = string.replace(/\^{2}/g, "");
    var index = string.indexOf("^"),
        result = "",
        state = true;

    while (index !== -1) {
        result += string.substring(0, index);
        if (state) {
            result += open;
        } else {
            result += close;
        }

        string = string.substring(index + 1);
        index = string.indexOf("^");
        state = !state;
    }

    return result + string;
}

var text = "Please select ^Continue^ to proceed with your call or ^Exit^ to call";

console.log(wrapMarked(text, "<font color='red'>", "</font>"));

jsfiddle