Borislav Hadzhiev
Sun Oct 31 2021·3 min read
Photo by Echo Grid
To convert a string to title case, call the replace()
method with the
following regular expression - /\w\S*/g
. As a second parameter to the replace
method, pass a function that takes every word in the string, converts the first
character to uppercase and the rest to lowercase.
function getTitleCase(str) { return str.replace(/\w\S*/g, word => { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }); } // 👇️ "One, Two, Three" console.log(getTitleCase('one, two, three'));
We passed the following 2 parameters to the String.replace method:
The forward slashes / /
mark the beginning and end of the regular expression.
The \w
special character matches latin characters [a-zA-Z]
, numbers [0-9]
and underscore _
.
The \S
character matches any single character other than white space.
The combination \w\S
matches one
in one two
.
The asterisk *
character matches the preceding item (word) 0
or more times.
g
(global) flag because we want to match all occurrences of space separated words in the string.If you need help reading a regular expression, check out this regex cheatsheet by the MDN docs, it has served me well over the years.
Each word will get passed to the function, where we convert the first character to uppercase and the rest to lowercase.
0
and the last - an index of string.length - 1
.The return value from the function serves as a replacement for each match (word) in the string. By converting each word to title case, we get a title cased string.
If you're not a fan of regular expressions, you can use a more functional approach.
To convert a string to title case:
split()
method.map()
method to convert each word to title case.join()
method to join the words into a single string.function getTitleCase(str) { return str .split(' ') .map(word => { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }) .join(' '); } // 👇️ "One, Two, Three" console.log(getTitleCase('one, two, three'));
We used the String.split method to get an array of the words in the string.
The parameter we passed to the method is the separator
- on which character
the string should be split.
We want to split the string into an array of words, so we passed in a string containing a space as the separator.
// 👇️ ['one', 'two', 'three'] console.log('one, two, three'.split(' '));
The next step is to use the Array.map method to iterate over the array.
Similarly to what we did previously, we uppercase the first character of each word and lowercase the rest.
The last step is to use the Array.join method to join the array of strings into a single string with a space separator.
This is a 3 step process: