2017-02-20 54 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