用RegExp替换单词时如何保持大小写?我正在使用此表达式:
token = "word";
text = "The Cow jumped over the moon. And the Dish ran away with the Spoon.";
value = text.replace(/\b\w\b/g, token);
//value = text.replace(/\b\w{1,}\b/g, token.charAt(0) + token.charAt(token.length-1));
//这导致
value == "word word word word word word. word word word word word word word word.";
//我想要的是
value == "Word Word word word word word. Word word Word word word word word Word.";
编辑:
reg exp匹配每个单词。
最佳答案
您可以在replace函数中使用条件返回。
显式专有名词
要仅过滤以大写字母开头的单词:
token = "word";
text = "The Cow jumped over the moon. And the Dish ran away with the Spoon.";
value = text.replace(/\b\w+\b/g, function(instance) {
if (instance.charAt(0) === instance.charAt(0).toUpperCase()) {
return token.charAt(0).toUpperCase() + token.substr(1, token.length - 1);
} else {
return token;
}
});
// Output: "Word Word word word word word. Word word Word word word word word Word."
混合大小写
如果您也想检测混合大小写,请使用条件
instance !== instance.toLowerCase()
(我将字符串更改为包含混合大小写的单词):token = "word";
text = "The Cow juMped over the mOON. And the Dish ran away with the Spoon.";
value = text.replace(/\b\w+\b/g, function(instance) {
if (instance !== instance.toLowerCase()) {
return token.charAt(0).toUpperCase() + token.substr(1, token.length - 1);
} else {
return token;
}
});
// Output: "Word Word Word word word Word. Word word Word word word word word Word."