Search code examples
javascriptstringcapitalizationcapitalize

Convert string to title case after dash or slash


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

Solution

  • 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"));