簡體   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