2016-06-25 31 views
-1

我幾乎無法在任何地方找到解決方案。是否有可能找到從startend以及裏面的所有內容。查找並替換字符串中的內容

var start = "/* Start: User One */"; 
var end = "/* End: User One */"; 

var userCSS = " 
/* Start: User One */ 
div.user_one {height: 700px;} 
/* End: User One */ 

/* Start: Storm */ 
div.storm {height: 500px;} 
/* End: Storm */"; 

我添加的開始和結束,因爲我已經提取它們,但我該怎麼做了startend搜索,然後一旦我開始和結束髮現我該怎麼辦從開始到結束取代所有內容。所以最好一次我發現了以下內容:

這是我期待的,最好能夠具有可變

/* Start: User One */ 
div.user_one {height: 700px;} 
/* End: User One */ 

來取代它,我可以用一個變量替換它。我覺得自從我在尋找開始和結束時,這必須是某種正則表達式的解決方案,但是我的正則表達式非常有限。

新的內容變量

/* Start: User One */ 
div.user_one {height: 500px;} 
div.user_one h1 {height: 500px;} 
/* End: User One */ 

輸入

/* Start: User One */ 
div.user_one {height: 500px;} 
/* End: User One */ 

/* Start: Storm */ 
div.storm {height: 500px;} 
/* End: Storm */"; 

預計輸出

/* Start: User One */ 
div.user_one {height: 500px;} 
div.user_one h1 {height: 500px;} 
/* End: User One */ 

/* Start: Storm */ 
div.storm {height: 500px;} 
/* End: Storm */"; 
+1

請加一些例子和代碼,你試過。 –

+0

什麼是替換變量?顯示更換後的預期結果 – RomanPerekhrest

+0

輸入是什麼?預期的輸出是什麼? –

回答

2

只是爲了試驗Ca SE必要的更換可以通過下面的正則表達式模式和String.replace功能來實現:

var start = "/* Start: User One */", 
    end = "/* End: User One */", 
    userCSS = "/* Start: User One */ div.user_one {height: 700px;}/* End: User One *//* Start: Storm */ div.storm {height: 500px;}/* End: Storm */", 
    newContent = "/* Start: User One */div.user_one {height: 500px;}div.user_one h1 {height: 500px;}/* End: User One */"; 

// you should always escape special characters in dynamic variables which are a part of a regular expression.  
var quote = function(str) { 
     return str.replace(/([.?*+^$[\]/(){}|-])/g, "\\$1"); 
    }, 
    re = new RegExp(quote(start) + "[^/]+" + quote(end)), 
    newCss = userCSS.replace(re, newContent); 

console.log(newCss); 

輸出:

/* Start: User One */div.user_one {height: 500px;}div.user_one h1 {height: 500px;}/* End: User One *//* Start: Storm */ div.storm {height: 500px;}/* End: Storm */ 
+0

這是完美的,但我可以包含在正則表達式中的開始/結束,所以它更動態? – DennisTurn

+1

是的,但請注意,您應該始終在屬於正則表達式的一部分的動態變量中轉義特殊字符。查看我的更新 – RomanPerekhrest

+0

我認爲這是我遇到的問題。你有任何例子如何逃脫開始/結束,然後我可以把它們動態地加入正則表達式? – DennisTurn