[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/ucfirst [Back]  [Original]

Uppercase the first character
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Uppercase the first character

    importance: 5

    Write a function ucFirst(str) that returns the string str with the uppercased first character, for instance:

    ucFirst("john") == "John";

    Open a sandbox with tests.

    solution

    We cant replace the first character, because strings in JavaScript are immutable.

    But we can make a new string based on the existing one, with the uppercased first character:

    let newStr = str[0].toUpperCase() + str.slice(1);

    Theres a small problem though. If str is empty, then str[0] is undefined, and as undefined doesnt have the toUpperCase() method, well get an error.

    The easiest way out is to add a test for an empty string, like this:

    function ucFirst(str) {
      if (!str) return str;
    
      return str[0].toUpperCase() + str.slice(1);
    }
    
    alert( ucFirst("john") ); // John

    Open the solution with tests in a sandbox.


    Web Proxy Viewer  |  New URL  |  Original Page