2015-07-18 75 views
5

我想要做的是编写一个函数来替换给定句子中的单个单词。其中一项要求是,被替换的单词的案例将与原始单词一样保留。在JavaScript中保留大小写的动态RegExp

我写了下面的功能:

function replace(str, before, after) { 
 
    var re = new RegExp('(\\.*)?(' + before + ')(\\.*)?', 'i'); 
 
    return str.replace(re, after); 
 
} 
 

 

 
// DEBUG 
 
console.log('----- DEBUG START -----'); 
 

 
var tasks = [ 
 
    replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"), 
 
    replace("Let us go to the store", "store", "mall"), 
 
    replace("He is Sleeping on the couch", "Sleeping", "sitting"), 
 
    replace("This has a spellngi error", "spellngi", "spelling"), 
 
    replace("His name is Tom", "Tom", "john"), 
 
    replace("Let us get back to more Coding", "Coding", "bonfires"), 
 
]; 
 

 
for (var i = 0; i < tasks.length; i++) { 
 
    console.log('Result #' + i + ': ' + tasks[i]); 
 
} 
 

 
console.log('----- DEBUG END -----');

一切工作正常,但事实上,该after字的情况是不一样的before单词的大小写旁边。

INFO:

我解决使用阵列(使用split()splice()indexOf()),并用一非动态RegExp()仅更换before元件同样的问题和情况下被保留下来。这就是为什么我不明白为什么我的其他解决方案不起作用。

回答

3

您正在用另一个字符串替换一串字符。 JS不会神奇地将原词的大写字母应用于替换词,因为这可能会导致潜在的不良行为。如果你必须保留角色的情况下,你需要走出去的方式来做到这一点。

如果你只关心第一个字母的大小写,你可以做的replace功能如下:

function replace(str, before, after) { 
 
    var b0 = before[0]; 
 
    after = after.replace(/^(.)/, function(a0){ 
 
    return b0.toUpperCase() === b0 ? a0.toUpperCase() : a0.toLowerCase(); 
 
    }); 
 
    var re = new RegExp('(\\.*)?(' + before + ')(\\.*)?', 'i'); 
 
    return str.replace(re, after); 
 
} 
 

 
// DEBUG 
 
document.write('----- DEBUG START -----<br>'); 
 

 
var tasks = [ 
 
    replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"), 
 
    replace("Let us go to the store", "store", "mall"), 
 
    replace("He is Sleeping on the couch", "Sleeping", "sitting"), 
 
    replace("This has a spellngi error", "spellngi", "spelling"), 
 
    replace("His name is Tom", "Tom", "john"), 
 
    replace("Let us get back to more Coding", "Coding", "bonfires"), 
 
]; 
 

 
    for (var i = 0; i < tasks.length; i++) { 
 
    document.write('Result #' + i + ': ' + tasks[i]+'<br>'); 
 
} 
 

 
document.write('----- DEBUG END -----');

+0

谢谢 - 我没有想到这一点。 – bx2

相关问题