【问题标题】:How to uppercase only i to I in the given string如何在给定字符串中将 i 大写到 I
【发布时间】:2022-11-24 00:25:19
【问题描述】:

如何在给定字符串中将 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)

【问题讨论】:

  • const res = string.split(' ').map(c => c === 'i' ? 'I' : c).join(' ');const res = string.replace(/(?<!\S)i(?!\S)/g, 'I');

标签: javascript regex


【解决方案1】:

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

console.log(string.replace(/i/g, 'I'));

【讨论】:

    【解决方案2】:

    您需要获取所有 i 单词并将它们替换为 I,所以试试这个:

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

    它会查找任何空格、标点符号或字符串的开头/结尾以找到单词“i”。然后它保留边界,并将“i”替换为“I”。

    【讨论】:

      【解决方案3】:

      您可以使用正则表达式:

      const caps = string.replace(/i/g, "I");
      

      【讨论】:

      • 它将所有的 i` 替换为 I,即使在 is 中也是如此
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2017-04-28
      • 2012-01-15
      • 2022-12-17
      • 1970-01-01
      • 2014-11-19
      • 2023-03-14
      相关资源
      最近更新 更多