Tell us what’s happening:
Ok, I got this working and the answer seems a little easier to read than some of the other posts. Thought I’d share for any new people struggling with this.
This line helped a lot, allows you to uppercase the first letter of a string.
upperStr = upperStr[0].toUpperCase() + upperStr.substring(1);
However I was also wondering if anyone knew if there was a way to do this with regular expressions, regex. I found one solution on the internet that I liked, it’s short and simple, however it doesn’t work with apostrophes - ', so failed this test. The \b boundary regular expression doesn’t seem to properly recognize ’ so it capitalizes before and after. In this case, the “I’m” becomes “I’M”.
Anyone know how this might work with regex?
Here’s the code:
function titleCase(str) {
let newStr = str.toLowerCase();
let reg = /\b\w/g;
// This code is good but doesn't work with ' in the words.
newStr = newStr.replace(reg,l => l.toUpperCase());
return newStr;
const titleCase = str =>
str
.toLowerCase()
.replace(/./, m => m.toUpperCase())
const titleCaseAll = str =>
str.replace(/\S*/g, m => titleCase(m))
titleCaseAll("I'm a little tea pot")
Here I make two assumptions:
titleCase() is makes any first character of a word to uppercase and rest to lowercase.
a word is a sequence of non-space characters.
I haven’t done any benchmarks, but this is exactly same as the version without using regex. Here, each regex just mimics str[0] and split(' ') respectively.