I.e., if I have an input string:
input = 'hello World, whatS up?'
I want an output string to be:
desiredOutput = 'Hello World, whats up?'
If the first letter of any word in the string is already in upper case, leave it as is.
I.e., if I have an input string:
input = 'hello World, whatS up?'
I want an output string to be:
desiredOutput = 'Hello World, whats up?'
If the first letter of any word in the string is already in upper case, leave it as is.
const upperCaseFirstLetter = string =>
`${string.slice(0, 1).toUpperCase()}${string.slice(1)}`;
const lowerCaseAllWordsExceptFirstLetters = string =>
string.replaceAll(/\S*/g, word =>
`${word.slice(0, 1)}${word.slice(1).toLowerCase()}`
);
const input = 'hello World, whatS up?';
const desiredOutput = upperCaseFirstLetter(lowerCaseAllWordsExceptFirstLetters(input));
console.log(desiredOutput);
Based on:
How do I make the first letter of a string uppercase in JavaScript?
and
How to capitalize first letter of each word, like a 2-word city?
word = word.charAt(0) + word.substring(1).toLowerCase();
I was trying to do the same and I found a shorter way to do it:
function formatString(str) {
return str
.replace(/(\B)[^ ]*/g, match => (match.toLowerCase()))
.replace(/^[^ ]/g, match => (match.toUpperCase()));
}
var text = "aaa BBB CCC";
console.log(formatString(text));
function titleCase(str) {
return str.split(' ').map(item =>
item.charAt(0).toUpperCase() + item.slice(1).toLowerCase()).join(' ');
}
console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
// It prints "Here Is My Handle Here Is My Spout";
Change the str
parameter values and you are good to go.