【发布时间】:2015-10-08 09:26:55
【问题描述】:
我想做的是编写一个函数来替换给定句子中的单个单词。其中一项要求是,被替换的单词的大小写将与原始单词一样保留。
我写了以下函数:
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 单词的大小写不同之外,一切正常。
信息:
我使用数组(使用split()、splice()、indexOf())解决了同样的问题,并且只用非动态RegExp() 替换了before 元素,并保留了案例。这就是为什么我不太明白为什么我的其他解决方案不起作用的原因。
【问题讨论】:
标签: javascript regex replace