Convert string to title case after dash or slash
Asked Answered
K

3

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();
    });
}
Kaila answered 4/5, 2017 at 14:33 Comment(0)
I
8

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"));
Impenetrability answered 4/5, 2017 at 14:37 Comment(0)
H
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'))
Hallucinogen answered 4/5, 2017 at 14:37 Comment(0)
B
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"));
Baudoin answered 29/5, 2020 at 23:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.