Javascript将字符串中每个单词的首字母大写

时间:2019-10-26 16:46:50

标签: javascript string

我有一个函数应该将字符串中每个单词的每个首字母大写,但是不知何故它传递了错误的结果,为什么?我需要修复一下。

所以输入:你好,多莉输出:你好,多莉。

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

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?"));

2 个答案:

答案 0 :(得分:0)

// 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?'))

答案 1 :(得分:0)

您可以使用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"));