Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    });
}
like image 719
Connie DeCinko Avatar asked May 04 '17 14:05

Connie DeCinko


People also ask

How to convert a string to title case in JavaScript?

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.

What is title case?

Title case is any text, such as in a title or heading, where the first letter of major words is capitalized.

How do you capitalize a string in JavaScript without ES6?

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.


3 Answers

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"));
like image 171
Jamiec Avatar answered Sep 30 '22 09:09

Jamiec


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'))
like image 32
Ja9ad335h Avatar answered Sep 30 '22 09:09

Ja9ad335h


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"));
like image 25
Richard Lovell Avatar answered Sep 30 '22 11:09

Richard Lovell