2016-11-01 35 views
1

幫手,這裏是我的挑戰:上找到的值由一個eval更換jQuery的正則表達式匹配

情況:(簡化的例子)

我有一個字符串,其中有不同的「參數」標有一定的語法,這取決於它的「類型」,這裏的「#和‘[...]’:

myString = "There are still #numberOfDays days until Christmas and it is already colder than #temperature degrees! I also have still have to buy [nrOfPresents] Christmas presents."

我有我的參數映射到值也是不同的方法,無論是直接值或具體公式:

myDict1 = {"numberOfDays" : 30, "temperature": -10, ...}; myDict2 = {nrOfPresents: "nrOfFriendsAndFamily - boughtPresents", ...};

問:

有沒有一種方法,對於每個參數類型的正則表達式選擇各參數,並與這需要一個函數的返回值來代替它找到的表達式作爲輸入?

到目前爲止我得到了: machesForType1 = myString.match(/#[A-Za-z]*(\b)/g),但這隻能給我比賽。

我想用類似mySting.replace(/#[A-Za-z]*(\b)/g , computeParameterFromArrayInfo([Whatever you find by using this regex expression here]))

任何想法?

PS:不同參數的數量相當高,因此對每個參數單獨評估並不是真正的選擇。

+0

難道你不會碰到你的字符串實際上需要這些標記之一的衝突嗎?他們相當普遍。 E.G'myString =「電話號碼是#phoneNumber」'?你有沒有看過Angular? – bassxzero

+0

我猜想,只要我確定,用標記,我只把它們當作字符串,不應該有任何衝突。你可能有更好的想法來標記可替換的東西嗎? – elior

+0

Angular2有一個相當廣泛的表情電梯,但它可能不是你要找的。 – bassxzero

回答

1

我終於解決了這個由各地工作:

var myNewString = myString; 

var foundParams = myString.match(/#[A-Za-z]*(\b)/g); // looking for all parameters with the marker "#" 

if (foundParams){ 
    for (var i = 0; i < foundParams.length; i++) { 
     var str2replace = foundParams[i]; 
     var param = str2replace.substr(1); // here: removing the marker "#" 
     var replacingStr = myMatchFunction(param); 
     myNewString = myNewString.replace(str2replace, replaicingStr); 
    } 

} 

,並重復此爲每個不同的參數類型,相應的調整。

0

你只需要更換replace方法中的回調:

var myNewString = "There are still #numberOfDays days (#no_replacing) until Christmas and it is already colder than #temperature degrees! I also have still have to buy [nrOfPresents] Christmas presents [no_replace_here]."; 
 
var myDict1 = {"numberOfDays" : 30, "temperature": -10}; 
 
var myDict2 = {"nrOfPresents" : "nrOfFriendsAndFamily - boughtPresents"}; 
 

 
myNewString = myNewString.replace(/#(\w+)|\[(\w+)]/g, function($0,$1,$2) { 
 
    if ($1 && myDict1[$1]) {  // If Group 1 matched and there is a key with tha value 
 
    return myDict1[$1];   // Replace with that value 
 
    } else if ($2 && myDict2[$2]) { // Else, if Group 2 matched and dict. 2 contains such a key 
 
    return myDict2[$2];   // Replace with the Dict. 2 value 
 
    } else return $0;    // Else, just re-insert the matched value back. 
 
}); 
 
console.log(myNewString);

#(\w+)|\[(\w+)]/g模式將匹配的# + 1或多個單詞字符出現多次拍攝到1組或[, 1組字符被捕獲到組2和]。匹配值組1和2傳入回調爲$0,$1$2(請參閱function($0,$1,$2))。他們被評估,你可以強制任何行爲基於什麼組匹配。有關邏輯的更多詳細信息,請參閱內聯代碼註釋。