在数组中大写第一个文本字母

时间:2014-02-18 19:57:36

标签: javascript capitalization

我们试图将一串多个单词拆分成一个单独的单词数组。我们希望将数组中的每个字符串大写。

var titleCase = function(txt) {
  var words = txt.split(" ");
  words.forEach(function(words) {
  if (words === "the" || words === "and") { 
    return words; 
  } else  {
    return words.charAt(0).toUpperCase() + words.slice(1);
  };
};

1 个答案:

答案 0 :(得分:3)

这里有几个语法错误和Array.forEach方法的错误用法。请尝试以下方法:

var titleCase = function(txt) {
  var words = txt.split(" ");
  words.forEach(function(word, idx, array) {
    if (word === "the" || word === "and") { 
      array[idx] = word; 
    } else  {
      array[idx] = word.charAt(0).toUpperCase() + word.slice(1);
    }
  });
  return words.join(" ");
};

console.log(titleCase("This is the test"));

JSFiddle example