2010-08-03 178 views
30

回調函數需要使用回調函數來代替<wiki>this page</wiki><a href='wiki/this_page'>this page</a>
更換比賽

text = text.replace(/<wiki>(.+?)<\/wiki>/g, function(match) 
    { 
     return "<a href='wiki/"+match.replace(/ /g, '_')+"'>"+match+"</a>"; 
    } 
); 

結果是標籤<wiki>被保留(全場比賽) - <a href='wiki/<wiki>this_page</wiki>'><wiki>this page</wiki></a>

有沒有辦法讓匹配[0],與[preg_replace_callback()]中的[1]匹配?

回答

62

replace function's callback將匹配作爲參數。

例如:

text = text.replace(/<wiki>(.+?)<\/wiki>/g, function(match, contents, offset, input_string) 
    { 
     return "<a href='wiki/"+contents.replace(/ /g, '_')+"'>"+contents+"</a>"; 
    } 
); 

(第二個參數是第一個捕獲組)

+1

工作。現在我知道JavaScript引用是 – Qiao 2010-08-03 11:12:21

+1

我認爲答案沒問題,但它太簡單了。同樣,匹配函數的最後兩個參數的順序似乎不正確。 請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter ,其中解釋了匹配函數接收的參數數目不定,具體取決於「括號內的子匹配[es]」的數量。 – user2367418 2017-09-11 19:45:00