Title Case a Sentence - 7/11/2018

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;

}

console.log(titleCase(“I’m a little tea pot”));

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

not sure how robust this is… I certainly wouldn’t dive for the regex here, but here’s what I came up with

/(?<=\b)(?<!')\w/g

Essentially what I went for is a lookbehind that has a word boundary, and a negative lookbehind that says the previous character isn’t an apostrophe

This then matches on the word character, and should let you use the replace function as you wanted

Edit: I should probably say that it’s a bad idea, in cases where you’d have a string like "'hello mark,' said john", but caveat emptor

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:

  1. titleCase() is makes any first character of a word to uppercase and rest to lowercase.
  2. 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.

You can also do it with /(\S)(\S*)/g

Thanks for the replies. I was thinking regex would have a simpler solution, but maybe that is not the case.