jasan jasan - 1 month ago 6
Javascript Question

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.

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

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

var input = 'hello World, whatS up?';
var desiredOutput = upperCaseFirstLetter(lowerCaseAllWordsExceptFirstLetters(input));

Based on:

How do I make the first letter of a string uppercase in JavaScript?

and

Javascript - How to capitalize first letter of each word, like a 2-word city?

Comments