我想做的是编写一个函数来替换给定句子中的单个单词。其中一项要求是替换单词的大小写将与原始单词一样保留。
我写了下面的函数:
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()
)解决了同样的问题,并且只替换了 before
元素与一个非动态 RegExp()
并且大小写被保留。这就是为什么我不太明白为什么我的其他解决方案不起作用。
最佳答案
您正在用另一个字符串替换一个字符串。 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 -----');
关于javascript - 在 JavaScript 中保留大小写的动态正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31496472/