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"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.