-2

我想使用正则表达式转换以下文本,以便将其中的文本^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 中使用正则表达式来实现上述目标?

4

3 回答 3

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"
于 2013-07-11T09:31:37.187 回答
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>")
于 2013-07-11T09:34:10.783 回答
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 上

于 2013-07-11T11:40:10.767 回答