5

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();
    });
}
Connie DeCinko
  • 996
  • 5
  • 19
  • 39

3 Answers3

7

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"));
Jamiec
  • 133,658
  • 13
  • 134
  • 193
3

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'))
Ja9ad335h
  • 4,995
  • 2
  • 21
  • 29
1

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"));
Richard Lovell
  • 848
  • 10
  • 18