Q:

Lowercase all letters in a string except the first letter and capitalize first letter of string ? -javascript

i.e If I have an input string:
input = 'hello World, whatS up?'
I want an output string:
desiredOutput = 'Hello World, whats up?'
If the first letter of any word in the string is already in Upper case , leave it as is. 

A:

Edited according to Apak's comment.

function upperCaseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function lowerCaseAllWordsExceptFirstLetters(string) {
    return string.replace(/\S*/g, function (word) {
        return word.charAt(0) + word.slice(1).toLowerCase();
    });
}

var input = 'hello World, whatS up?';
var 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?

A:

word = word.charAt(0) + word.substring(1).toLowerCase();

A:

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));

