2010-05-17 74 views
1

我需要實現是令牌替換在JavaScript

在字符串中查找模式,店面的比賽替代的獨特標記的比賽,這樣以後在令牌可以通過其早期發現比賽被替換。

爲了解釋

爲eample我有圖案提取賽後數組

paterns = [/Mr\.\s/,/Mrs\.\s/]; 


stringSubject = "Mr. john is an expert. mrs. john is no less. mr. watson know this very well"; 

它可能看起來像(不區分大小寫匹配)

stringSubject = "{1} john is an expert. {2} john is no less. {3} watson know this very well"; 

和令牌陣列看起來像

tokens = ["Mr.","mr.","mrs."] 

stringSubject = "{1} john is an expert. {3} john is no less. {2} watson know this very well"; 

//處理stringSubject

令牌之後被替換,使得

stringSubject = "Mr. john is an expert. mrs. john is no less. mr. watson know this very well"; 

使原本串被檢索,因爲它甚至對於匹配模式執行大小寫不敏感的操作之後是。

這怎麼可以用正則表達式來完成?

回答

2

這是怎麼回事?

var stringSubject = "Mr. john is...", 
    patterns = [/Mr\.\s/, /Mrs\.\s/], 
    currentTokenIndex = 0, 
    tokens = [/* this is where the matches will be stored */]; 

for (var i = -1, l = patterns.length; ++i < l;) { 
    stringSubject = stringSubject.replace(patterns[i], function(match){ 
     tokens[currentTokenIndex] = match; 
     return '{' + currentTokenIndex++ + '}'; 
    }); 
} 

stringSubject; // <= "{0}john is..." 

// Later: 
stringSubject = stringSubject.replace(/\{(\d+?)\}/g, function(match, index){ 
    return tokens[index]; 
}); 

stringSubject; // <= "Mr. john is..." 
+0

謝謝這個作品! – Sourabh 2010-05-17 17:17:44