I use this common function to convert most of my list items to title case with no issues. I've discovered one place that needs improvement, when there is a dash or slash in the middle, I want the next letter capitalized.
For example Hispanic/latino should be Hispanic/Latino. Basically capitalize when the first letter or proceeded by a symbol OR a space.
Current code:
function toTitleCase(str) {
return str.toLowerCase().replace(/(?:^|\s)\w/g, function (match) {
return match.toUpperCase();
});
}
In JavaScript, there is no direct way of converting a string to title case. However, the combination of multiple methods can solve the problem. Let’s convert capitalize first letter of each word together. There are several ways of converting. One of the methods is the map () method.
Title case is any text, such as in a title or heading, where the first letter of major words is capitalized.
or without ES6: function capitalize (str) { return str.charAt (0).toUpperCase () + str.substring (1, str.length).toLowerCase (); } function titleCase (str) { return str.replace (/ [^\ \/\-\_]+/g, capitalize); } console.log (titleCase ("I'm a little/small tea pot.")); Show activity on this post.
Just change your capture of whitespace \s
, to be a class of characters being whitespace, a hyphen or a slash [\s-/]
(and anything else you want)
function toTitleCase(str) {
return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) {
return match.toUpperCase();
});
}
console.log(toTitleCase("test here"));
console.log(toTitleCase("test/here"));
console.log(toTitleCase("test-here"));
just add or conditions in regex /(?:^|\s|\/|\-)\w/g
function toTitleCase(str) {
return str.toLowerCase().replace(/(?:^|\s|\/|\-)\w/g, function (match) {
return match.toUpperCase();
});
}
console.log(toTitleCase('His/her new text-book'))
Here's a solution that strips the dashes. So for the following input:
list-item
It returns:
ListItem
An extension of Jamiec's solution that will achieve this is:
function toTitleCase(str) {
return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) {
return match.toUpperCase();
}).replace('-', '');
}
console.log(toTitleCase("list-item"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With