用字符串大写数组的第一个字母

时间:2019-06-22 02:43:49

标签: javascript

我试图用字符串将大写的第一个字母大写,我将方法添加到String中,但是它只返回大写的第一个字母,而不是整个句子。所以应该是“嗨,你好吗?”

const str = "Hi there how are you?";

String.prototype.toJadenCase = function(st) {
  let arr = st.split(" ");
  arr.forEach(function(ele, index) {
    arr[index] = ele.charAt(0).toUpperCase();
  });
  return arr;
};

console.log(String.prototype.toJadenCase("Hi there how are you"));

仅返回第一个字母而不是完整单词[“ H”,“ T”,“ H”,“ A”,“ Y”]的数组

1 个答案:

答案 0 :(得分:2)

您还需要添加字符串的其余部分

const str = "Hi there how are you?";

String.prototype.toJadenCase = function (st) {
    let arr = st.split(" ");
    arr.forEach(function(ele, index) {
        arr[index] = ele.charAt(0).toUpperCase() + ele.substr(1)
    });
    return arr;
};

console.log(String.prototype.toJadenCase("Hi there how are you"));

Prototype上添加方法不是一个好习惯,您可以简单地编写一个函数并使用它

const str = "Hi there how are you?";

const changeFirstChar = (str) => str[0].toUpperCase() + str.substr(1)

const toJadenCase = function(st) {
  let arr = st.split(" ");
  return arr.map(e => changeFirstChar(e))
};

console.log(toJadenCase("Hi there how are you"));

//if you need output as string
console.log(toJadenCase("Hi there how are you").join(' '));