此问题在此处已有答案:
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
行为?
2条答案
按热度按时间iyfjxgzm1#
xoefb8l82#
你需要得到所有的
i
单词,并将它们替换为I
,所以可以这样做:它会寻找任何空白、标点符号或字串的开头/结尾,以寻找单字'i'。然后,它会保留边界,并以'I'取代'i'。