Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I lowercase any string then capitalize only the first letter of the word with Javascript? [duplicate]

Tags:

javascript

I'm not sure if I did this right, as I am pretty new to JavaScript.

But I want to lowercase any random string text and then capitalize the first letter of each word in that text.

<script>
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    function lowerCase(string) {
        return string.toLowerCase();
    }
</script>
like image 991
dancemc15 Avatar asked May 03 '16 06:05

dancemc15


People also ask

How do you capitalize the first letter of a word in JavaScript?

Use the built-in method toUpperCase() on the letter you want to transform to uppercase.

How do you capitalize the first letter of a string in Java?

In order to pick the first letter, we have to pass two parameters (0, 1) in the substring() method that denotes the first letter of the string and for capitalizing the first letter, we have invoked the toUpperCase() method. For the rest of the string, we again called the substring() method and pass 1 as a parameter.

How will you convert a string to all lowercase and how will you capitalize the first letter of string?

The toLowerCase method converts a string to lowercase letters. The toLowerCase() method doesn't take in any parameters. Strings in JavaScript are immutable. The toLowerCase() method converts the string specified into a new one that consists of only lowercase letters and returns that value.


1 Answers

Just change the method to

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

.toLowerCase() is appended to the last method call.

This method will make the first character uppercase and convert rest of the string to lowercase. You won't need the second method.

like image 75
gurvinder372 Avatar answered Sep 21 '22 06:09

gurvinder372