Here’s a useful way to use the regular expression that Felgall provided before.
I’ve unpacked his example with a few named variables and functions, to help make it easier to talk about the code and understand what it does.
function upperCase(str) {
return str.toUpperCase();
}
function titleCase(str) {
var firstLetterRx = /(^|\s)[a-z]/g;
return str.replace(firstLetterRx, upperCase);
}
var result = titleCase("help i'm sick"); // "Help I'm Sick"
The firstLetterRx is a regular expression (thus the rx naming convention) that matches starting lowercase letters.
Here’s a railroad diagram that shows the structure of the regular expression:
/(^|\s)[a-z]/g
/…/g
The forward slashes delimit the regular expression itself. Normally a regular expression gives you only the first match, so the letter g afterwards says that it does a global match across the whole string, finding all matching situations in the string.
(^|\s)
The (^|\s) part is a group that looks for two different types of situations. The ^ symbol is an anchor that matches the position before the start of a string, and the \s is a character class that represents whitespace, which could be tabs, newlines, or just spaces too. The | symbol results in alternation, so that either of the anchor or the whitespace class are considered to be a valid match.
##(…)
The parenthesis also form what is called a capture group, but we’re not using that in this situation. Capture groups let you use \1 and \2 notation to replace a captured section of a string with another string. Instead of doing that, we are only using the parenthesis to gain the benefit of using alternation, so that we can match both the whitespace before a character, as well as the first letter of a string.
##[a-z]
The [a-z] part of the regular expression is a character class, that says any lowercase letter from a through to z is considered valid.
##Matched strings
When the regular expression is used on a string, such as “help i’m sick”, it will result in a certain number of matches within that string. In this case those matches are, “h”, " i", and " s".
That’s the job of the regular expression all finished.
##The replace method
From here, the replace method passes those matched strings to a replacement function that we have called upperCase. Those strings return from it converted to uppercase, and the replace method replaces the original parts of the string that it found, with the returned result from the replacement function.
As you can see, str.replace(firstLetterRx, upperCase);
does all of the work to achieve title case of the string.