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();
});
}
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"));
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.