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
元件同样的问题和情况下被保留下来。这就是为什么我不明白为什么我的其他解决方案不起作用。
谢谢 - 我没有想到这一点。 – bx2