Reputation: 373
I am attempting to convert any string that I have into a title case format. I am able to accomplish this for titles without any hyphens. When a hyphen is introduced I am getting a s.match(...) is null
error. I've attempted to adjust the code below but I have been unsuccessful. How can I adjust the function below in order to handle not only regular strings but when a hyphen is introduced.
I have 2 examples in my code snippet. First firstTitle
, is a basic string that is converted the way I am expecting it to. Second, secondTitle
is an example when a hyphen is introduced and is erroring.
My expected outcome is for secondTitle
to return back as : Retail Sales - Online Order
let firstTitle = "Testing string to title case"
let firstCase = firstTitle .toLowerCase().split(' ').map(function (s) {
let letterToCapitalize = s.match(/\w/)[0];
return s.replace(letterToCapitalize, letterToCapitalize.toUpperCase())
}).join(' ');
console.log(firstCase )
let secondTitle= "Retail sales - online order"
let secondCase= secondTitle.toLowerCase().split(' ').map(function (s) {
let letterToCapitalize = s.match(/\w/)[0];
return s.replace(letterToCapitalize, letterToCapitalize.toUpperCase())
}).join(' ');
console.log(secondCase)
Upvotes: 0
Views: 929
Reputation: 24965
let secondTitle = "Retail sales - online order";
let secondCase = secondTitle.toLowerCase().replace(/\b[a-z]/g, function (s) {
return s.toUpperCase();
});
console.log(secondCase);
Rather than splitting the string, you can replace all the lowercase characters. If you use the boundary anchor followed by the alpha set, you can match the first character of the string and any character preceeded by whitespace. Then all you have to do is uppercase it.
Upvotes: 2