문제

We're trying to split up a string of multiple words into an array of individual words. We want to capitalize each individual string within the 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);
  };
};
도움이 되었습니까?

해결책

There are several syntax errors, and incorrect usage of the Array.forEach method here. Try the following:

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top