You can use the replace function to ascertain if a letter is upper case and return a prefixed space with the character if it is, while simultaneously making sure that the first character is capitalized.
key.replace(/[a-z]/gi, (m, o) => (m < {} && o) ? ` ${m}` : (o) ? m : m.toUpperCase())
Brief Explanation
You can determine whether or not a character is capitalized by comparing it to {}
. If a character is less than it is capitalized, and if it is greater than it is lower case. This is because {}
will be transformed to the string [object Object]
, and both the character codes will be compared. Upon comparison only the first character will be used("["). Thus "A" < "["
and "A" < {}
is equivalent. This is easier explained through seeing their character codes:
"A".charCodeAt(0);
//65
"[".charCodeAt(0);
//91
"a".charCodeAt(0);
//97
(In fact, it's more performant to use "[", and for optimization you would compare to that instead. It's simply easier to remember "{}" is greater than capital characters and vice versa)
Why do this?
In typical RegEx you could simply use [A-Z]
to grab capitalized characters, but the caveat is that if you're looking to capitalize the first character AND space camel case, this comparison in addition to the offset
parameter( think of it as an index of the string ) in the replace
function allows you to do so in a singular pass through the string.
An Example:
let splitCase = key => key.replace(/[a-z]/gi, (m, o) => (m < "[" && o) ? ` ${m}` : (o) ? m : m.toUpperCase());
let key = "phoneNumber";
console.log(splitCase(key));
key = "firstName";
console.log(splitCase(key));
In Your Code:
The below snippet is non-functioning, but it should work within your code:
function sendAppliedEmail(applicant) {
let splitCase = (key) => key.replace(/[a-z]/gi, (m, o) => (m < "[" && o) ? ` ${m}` : (o) ? m : m.toUpperCase());
let html = '<img src="" alt="logo">';
html += '<h2 style="color: black">New Applicant</h2>'
html += '<ul>';
Object.entries(applicant).forEach(([key, value]) => {
html += `<li>${splitCase(key)}: ${value}</li>`;
});
html += '</ul>';