In JavaScript, converting a string to title case involves capitalizing the first letter of each word and making all other letters lowercase. This is commonly used for formatting text in user interfaces, such as headings, titles, and names.
To achieve this, you can use the replace()
method with a regular expression that matches each word in the string. The replacement function will take the matched word, capitalize its first letter using charAt(0).toUpperCase()
, and make all other letters lowercase using substring(1).toLowerCase()
.
Here’s an example implementation:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
text => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase()
);
}
const example = 'john smith';
console.log(`"${example}" becomes "${toTitleCase(example)}"`);
This code defines a toTitleCase
function that takes a string as input and returns the title-cased version. The regular expression /\w\S*/g
matches each word in the string, where \w
matches any word character (alphanumeric plus underscore) and \S*
matches zero or more non-space characters.
Alternatively, you can use the split()
method to split the string into words, then use map()
to transform each word to title case, and finally join the words back together using join()
:
const str = "foo bar baz";
const newStr = str.split(' ')
.map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())
.join(' ');
console.log(newStr);
Note that this approach assumes that the input string only contains spaces as word separators. If you need to handle other types of word separators, such as tabs or newline characters, you may need to modify the regular expression or splitting approach accordingly.
It’s also worth noting that some CSS solutions can achieve similar results using the text-transform
property with a value of capitalize
. However, this approach has limitations, such as not handling all caps or mixed case input correctly.
text-transform: capitalize;
For more advanced use cases, you may want to consider implementing a custom title casing function that handles specific edge cases, such as preserving acronyms or minor words. One example implementation is provided below:
String.prototype.toTitleCase = function() {
var i, j, str, lowers, uppers;
str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain minor words should be left lowercase unless
// they are the first or last words in the string
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
for (i = 0, j = lowers.length; i < j; i++)
str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'),
function(txt) {
return txt.toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
return str;
}
This implementation provides a more comprehensive title casing solution that handles various edge cases and can be used as a starting point for your specific use case.