Domanda

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);
  };
};
È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top