繁体   English   中英

将数组中的第一个字母大写

[英]Capitalizing first letter of text within array

我们正在尝试将多个单词的字符串分成单个单词的数组。 我们要大写数组中的每个字符串。

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);
  };
};

这里有一些语法错误,以及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示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM