javascript - 如何使用 RegExp 保持大小写?

标签 javascript regex actionscript-3

用正则表达式替换单词时如何保持大小写?我正在使用这个表达式:

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/

相关文章:

javascript - 使用 jQueryUI 对话框,如何获取打开对话框的元素?

java - 你如何使用 java(不是 javamail)连接到你的电子邮件

javascript - 将复选框加载/删除到数组时出现问题

regex - pig : extracting email details from raw text using REGEX

javascript - 调用函数用正则表达式替换某些子字符串的问题

python - 如何提取特定单词后的行?

javascript - 一款javascript石头剪刀布游戏!

c# - 如何使用 ColorMatrix 为图像的每个像素设置相同(恒定)的色调值?

algorithm - 游戏网络延迟补偿

Flash 开发 - 发布