【问题标题】:Javascript capitilizing first letter in each word in a string [duplicate]Javascript将字符串中每个单词的首字母大写[重复]
【发布时间】:2020-02-22 15:29:47
【问题描述】:

我有一个函数应该将字符串中每个单词的第一个字母大写,但不知何故它提供了不正确的结果,知道为什么吗?我需要修复一下。

所以输入:hello dolly 输出:Hello Dolly。

空格计算正确,但大小写不正确。

function letterCapitalize(str) {
  str = str.replace(str.charAt(0), str.charAt(0).toUpperCase());
  let spaces = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i] === ' ') spaces.push(i);
  }
  for (let space of spaces) {
    str = str.replace(str.charAt(space + 1), str.charAt(space + 1).toUpperCase());
  }
  return str;
}

console.log(letterCapitalize("hello there, how are you?"));

【问题讨论】:

  • 我知道 replace 仅替换第一次出现,但我应该如何使其正常工作?
  • 你的函数和.toUpperCase()有什么区别?
  • const letterCapitalize = x =&gt; x.toUpperCase();
  • const letterCapitalize = x =&gt; x.replace(/[a-zA-Z]/g, l =&gt; l.toUpperCase())
  • @Tibike 在字符类中不需要 A-Z,因为 OP 正在尝试更改为大写,所以 /[a-z]/ 就足够了

标签: javascript string


【解决方案1】:

// Option One

function capitalize1( str ) {
  let result = str[ 0 ].toUpperCase();

  for ( let i = 1; i < str.length; i++ ) {
    if ( str[ i - 1 ] === ' ' ) {
      result += str[ i ].toUpperCase();
    } else {
      result += str[ i ];
    }
  }

  return result;
}

// Option Two

function capitalize2(str) {
  const words = [];

  for (let word of str.split(' ')) {
    words.push(word[0].toUpperCase() + word.slice(1));
  }

  return words.join(' ');
}

console.log(capitalize1('hello there, how are you?'))
console.log(capitalize2('hello there, how are you?'))

【讨论】:

  • 耶!就是这样,这正是我所需要的......我想知道为什么我想不惜一切代价使用替换,这更简单。谢谢@mplungjan
  • 也谢谢@SakoBu
【解决方案2】:

您可以使用string.toUpperCase(),或者如果您需要更具体的逻辑,您可以使用带有一些正则表达式的string.replace()

const letterCapitalize = x => x.toUpperCase();

const letterCapitalizeWithRegex = x => x.replace(/[a-z]/g, l => l.toUpperCase());

console.log("my string".toUpperCase());

console.log(letterCapitalize("my string"));

console.log(letterCapitalizeWithRegex("my string"));

【讨论】:

  • 问题已调整,我只需要字符串的每个第一个字母,而不是所有字符
猜你喜欢
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 2010-11-12
  • 2011-01-20
  • 2014-05-19
  • 2021-09-07
  • 2010-12-05
相关资源
最近更新 更多