2012-06-09 56 views
1

先生, 我是做用JavaScript。我的一個項目想與regex.in一個段落,以取代文本,我想使用JavaScriptJavascript和正則表達式替換文本

替換一些詞如:

var str =" Would you like to have responses to your questions |code Would you like to have responses to your questions code| Would you like to have responses to your questions " 

var n=str.replace("to","2"); 

這裏所有的「」將replaced.We不想之間刪除|代碼代碼|請幫助我的任何一個.....

回答

1

我認爲你不應該依賴這些類型的任務正則表達式,因爲它會過於複雜,因此緩慢。無論如何,如果你的表達是正確的(即,對於每一個"|code"有一個"code|"有沒有嵌套code標籤),你可以試試這個:

var n = str.replace(/to(?!(?:\|(?!code)|[^\|])*code\|)/g, "2"); 

不僅是複雜的,但它很難維持。在這些情況下做的最好的事情是你的字符串分割,以塊:

var chunks = [], i, p = 0, q = 0; 
while ((p = str.indexOf("|code", p)) !== -1) { 
    if (q < p) chunks.push(str.substring(q, p)); 
    q = str.indexOf("code|", p); 
    chunks.push(str.substring(p, p = q = q + 5)); 
} 
if (q < str.length) chunks.push(str.substring(q)); 

// chunks === [" Would you like to have responses to your questions ", 
//    "|code Would you like to have responses to your questions code|", 
//    " Would you like to have responses to your questions "] 

注:str.replace("to", "2")取代"to"每一次出現,但只有第一個。

0

,如果你想將所有「到」更換成2,這將是代碼

var str =" Would you like to have responses to your questions |code Would you like to have responses to your questions code| Would you like to have responses to your questions"; 
var n=str.replace(/to/g,"2");