用正则表达式替换单词时如何保持大小写?我正在使用这个表达式:
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 匹配每个单词。
最佳答案
您可以在替换函数中使用条件返回。
显式专有名词
仅过滤以大写字母开头的单词:
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."
关于javascript - 如何使用 RegExp 保持大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576711/