使用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匹配每个单词。
答案 0 :(得分:1)
您可以在替换函数中使用条件返回。
仅过滤以大写字母开头的单词:
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."
答案 1 :(得分:1)
你也可以像这样的正则表达式
str = str.replace(/\b\w+\b/g, function(m){
return /^[A-Z]/.test(m) ? "Word" : "word"
});
答案 2 :(得分:0)
我建议分两个阶段进行
/\b[A-Z][a-z]*\b/Word/g
然后
/\b[a-z]*\b/word/g
警告 -
MixedCase
和ALLCAPS
。