Basic Algorithm Scripting: Title Case a Sentence (better regex than given solution?)

Basic Algorithm Scripting: Title Case a Sentence (better regex than given solution?)
0

#1

Hello,

I did solve this problem on my own without using regex, however noticed the ‘advanced’ solution does use Regex and is very similar to my solution. This is the solution that I am speaking of:

return str.toLowerCase().replace(/(^|\s)\S/g, char => char.toUpperCase());

While the solution works perfectly for this case, this regex also captures the spaces preceding the first character in the words. I was wondering if there was regex code that can capture only the character and not the space proceeding it (might be useful in a future scenario?)? I did some experimenting with positive lookbehind (?<=…) but I could not get it to work (I tested in node.js)t. I’ve searched around stack overflow and such but didn’t find a solution that I could understand or implement. Google searches said lookbehinds are not well supported in Javascript at the moment, but I could get simpler lookbehinds to work (such as capturing ‘cat’ from ‘1cat’ using /(?<=\d)cat/). Surely then, I could capture the first character ONLY immediately following a space (\s) but not the space itself like the given solution does? The first character in the string must also be captured…

Just curious if it can be done currently in Javascript? Thank you!


#2

OK well its one of those situations where talking about it and asking for help resulted in me finding my own solution. I’ll share it below for those curious (and because I’m happy about getting it!):

/^\S|(?<=\s)\S/ig

(the ig flags at the end are obviously optional depending on your needs…)

My regex understanding needs work, but if I am not mistaken, this breaks down to:
^\S === ‘capture the first non space character in the string’.
| === ‘or’.
(?<=\s)\S === 'find a nonspace character (\S) preceded by a space character (\s).

Note that this solution doesn’t seem to work on the actual problem on FCC, but does work when tested in node.js. Probably has something to do with that ‘lookbehinds are not fully supported yet in JS’. Maybe someone else will find it interesting/useful!