17

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dancemc15
  • 598
  • 2
  • 7
  • 21

2 Answers2

21

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.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • 4
    @dancemc15 your question says `But I want to lowercase any random string text and then capitalize the first letter of each word in that text.` But the answer you have accepted is only making the first letter capital. It is not making the rest of the string in lowercase. – gurvinder372 May 03 '16 at 06:41
  • 2
    function ucFirst(string) { if (!string || typeof string !== 'string') return ''; return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } – Anthony Awuley Sep 30 '20 at 18:24
1

A small sample:

function firstLetter(s) {

  return s.replace(/^.{1}/g, s[0].toUpperCase());
}

firstLetter('hello'); // Hello
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47