Automated title capitalization with JavaScript
Last updated: September 27, 2022.
You can add title capitalization to a string automatically using JavaScript by splitting a string, modifying it and then rejoining the output.
Table of contents
Basic capitalization
To do basic capitalization, split a string into an array by empty spaces. Then, loop through the array to capitalize the first letter of each item. Join this capitalized first letter to the rest of the word and push the result into a new array. Finally, join the new array to make a new string:
/* Basic capitalization */
function titleCapitalize(inputString) {
// Convert input to lower case and split into array of words
inputString = inputString.toLowerCase().split(' ');
const outputArray = []; // New array to push items to
for (let i = 0; i < inputString.length; i++) {
const firstLetter = inputString[i].charAt(0).toUpperCase(); // Save first letter of each word capitalized
const remainingLetters = inputString[i].slice(1); // Save rest of word
const capitalizedWord = firstLetter + remainingLetters; // Concatonate first letter and rest of word
outputArray.push(capitalizedWord); // Push result to new array
}
const outputString = outputArray.join(' '); // Join words in new array to form string
return outputString; // Make formed string the return value
}
const res = titleCapitalize("to kill a mocking bird");
console.log(res); // To Kill A Mocking Bird
Capitalization with exceptions
The above code capitalizes the first letter of each word in a string no matter what.
But some words are not usually capitalized.
To add exceptions, create an array of exception words and check before a word is capitalized if it matches any of the words in the exceptions array. If so, capitalization is skipped and the word is pushed without modification into the new array.
But capitalization is not skipped if a word is the first in a title, even if it is an exception word.
/* Capitalization with exceptions */
function titleCapitalize(inputString) {
const exceptions = ["a", "an", "the", "of", "and", "but", "or", "for", "nor", "in", "to"];
inputString = inputString.toLowerCase().split(' ');
const outputArray = [];
for (let i = 0; i < inputString.length; i++) {
if (exceptions.includes(inputString[i]) && i !== 0) { // if word is an exception and is not first word in title
outputArray.push(inputString[i]);
} else { // capitalize word
const firstLetter = inputString[i].charAt(0).toUpperCase();
const remainingLetters = inputString[i].slice(1);
const capitalizedWord = firstLetter + remainingLetters;
outputArray.push(capitalizedWord);
}
}
const outputString = outputArray.join(' ');
return outputString;
}
const res = titleCapitalize("to kill a mocking bird");
console.log(res); // To Kill a Mocking Bird
The exceptions array above only covers common cases. But extra words can be added for more nuanced behavior.