regex 如何在给定的字符串中只将i大写为I [duplicate]

14ifxucb  于 2022-11-26  发布在  其他
关注(0)|答案(2)|浏览(140)

此问题在此处已有答案

How can I match a whole word in JavaScript?(4个答案)
2天前关闭。
如何在给定字符串中仅将'i'大写为'I':

const string = 'i have this. if i am. you and i and it is i';

我写了这个但我认为一定有一个更好更明确的解决办法:

const string = 'i have this. if i am. you and i and it is i';

const res = string.split(' ').map(w => {
    if(w == 'i') return 'I';
  return w;
}).join(' ');

console.log(res)

我应该使用什么正则表达式来模拟这个map行为?

iyfjxgzm

iyfjxgzm1#

const string = 'i have this. if i am. you and i and it is i';

console.log(string.replace(/\bi\b/g, 'I'));
xoefb8l8

xoefb8l82#

你需要得到所有的i单词,并将它们替换为I,所以可以这样做:

const replaceI = string.replace(/(\s|^|\.|,|\!|\?)i(\s|$|\.|,|\!|\?)/gm, "$1I$2");

它会寻找任何空白、标点符号或字串的开头/结尾,以寻找单字'i'。然后,它会保留边界,并以'I'取代'i'。

相关问题