2013-07-11 29 views
-2

我想使用正則表達式將以下文本轉換爲^text^中的文本被某些HTML標記中的文本替換。 (內<font color='red'></font>在HTML中使用正則表達式使用正則表達式着色文本

例子:

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中使用正則表達式

+1

你嘗試過什麼?這個文本是在DOM的某個地方還是一個字符串,你稍後會添加到DOM中? – Xotic750

+0

請顯示您到目前爲止所嘗試的內容。 – Sumurai8

回答

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
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" 
+0

你也可以使用一個否定類'[^^]'而不是懶惰星))) – georg

+0

我在這裏使用這個懶惰的星只是因爲你最近的評論:D 試圖變得不可預測:) – mishik

+0

是的,你有一種混淆我的頭髮分裂引擎的方法。 – georg

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