2017-02-20 100 views
0

我有一個場景,其中文本塊包裝相同,但他們的正則表達式轉換不相同。替換函數結合if語句

而不是近乎重複的替換調用,我希望在替換中使用函數回調。但是,似乎我不能使用$ 1等?它只是從字面上打印出「$ 1」,而不是捕獲組。

console.log(
 
    ('{{text1}} blah blah blah blah blah blah {{para2}}').replace(/\{\{(\w+)(\d+)\}\}/g, function(match){ 
 
    \t if ('$1' === "text") { 
 
    \t \t return '[$1/$2]'; 
 
    \t } else { 
 
    \t \t return '[$1----$2]'; 
 
    \t } 
 
    }) 
 
);

應該產生:

'[text/1] blah blah blah blah blah blah [para----2]' 

但目前生產:

'[$1/$2] blah blah blah blah blah blah [$1----$2]' 

回答

2

如果你是pass a function into replace,它將捕獲的組作爲完全匹配參數後的位置參數。它不會嘗試解釋函數返回的字符串。

您可以通過採取在函數的參數,並使用它們來構建要返回字符串解決您的問題:

('{{text1}} blah blah blah blah blah blah {{para2}}').replace(/\{\{(\w+)(\d+)\}\}/g, function(match, p1, p2){ 
    if (p1 === "text") { 
     return '[' + p1 + '/' + p2 + ']'; 
    } else { 
     return '[' + p1 + '----' + p2 + ']'; 
    } 
}); 
0

捕獲作爲函數的參數傳遞。你可以閱讀更多關於它的MDN

('{{text1}} blah blah blah blah blah blah {{para2}}').replace(/\{\{(\w+)(\d+)\}\}/g, function(match, $1, $2){ 
    if ($1 === "text") { 
     return '[' + $1 + '/' + $2 + ']'; 
    } else { 
     return '[' + $1 + '----' + $2 + ']'; 
    } 
}); 

功能通過捕獲作爲參數function(match, $1, $2)

+0

'如果( '$ 1' === 「文本」)'或許會永遠不會計算爲true – maksymiuk

+0

是的,我沒有看到一個。我已經更新了答案 – Joe

0
('{{text1}} blah blah blah blah blah blah {{para2}}').replace(/\{\{(\w+)(\d+)\}\}/g, function(match,patt,index){ 

    if (patt === "text") { 
     return '['+patt+'/'+index+']'; 
    } else { 
     return '['+patt+'----'+index+']'; 
    } 
}); 

在功能參數替換法回報指數和匹配值,因爲我使用。

0

您需要parse the arguments或者,如果你知道電話號碼,就可以讓他們作爲固定的參數:

console.log(
 
    ('{{text1}} blah blah blah blah blah blah {{para2}}') 
 
    .replace(/\{\{(\w+)(\d+)\}\}/g, 
 
    function(match, capture1, capture2) { 
 
     if (capture1 === "text") { 
 
     return '[' + capture1 + "/" + capture2 + ']'; 
 
     } else { 
 
     return '[' + capture1 + '----' + capture2 + ']'; 
 
     } 
 
    }) 
 
);

0

僅當replace()函數中的替換參數是字符串時,纔有10個變量可用。在功能的情況下,捕獲的內容將通過函數中的參數訪問。因此,子匹配的數量提供了函數中的參數數目。

console.log(
 
    ('{{text1}} blah blah blah blah blah blah {{para2}}').replace(/\{\{(\w+)(\d+)\}\}/g, function(match,p1,p2){ 
 
    \t if (p1 === "text") { 
 
    \t \t return '['+p1+'/'+p2+']'; 
 
    \t } else { 
 
    \t \t return '['+p1+'----'+p2+']'; 
 
    \t } 
 
    }) 
 
);

參考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace