Skip to content

JavaScript uppercase first letter | Example code

  • by

The best way to make the uppercase first letters is through a combination of two functions in JavaScript. One function is used to uppercase the first letter and the second function slices the string and returns it starting from the second character.

str.charAt(0).toUpperCase() + name.slice(1)

JavaScript uppercase first letter

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    function upCase(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }

    console.log(upCase('hello woRld toUpperCase'));
  </script>
</body>
</html> 

Output:

JavaScript uppercase first letter

How to capitalize the first letter and lowercase the rest of the string?

Answer: Just capitalize the first letter and concatenate that to the rest of the string converted to lowercase.

function titleCase(string){
  return string[0].toUpperCase() + string.slice(1).toLowerCase();
}
console.log(titleCase('Download Price History'));

Output: Download price history

Using regular expressions:

function capitalizeFirstLetter(inputString) {
  return inputString.replace(/^\w/, (match) => match.toUpperCase());
}

const originalString = "hello world";
const capitalizedString = capitalizeFirstLetter(originalString);
console.log(capitalizedString); // Output: "Hello world"

You only need to capitalize the first letter and concatenate that to the rest of the string converted to lowercase.

function titleCase(string){
  return string[0].toUpperCase() + string.slice(1).toLowerCase();
}
console.log(titleCase('Download Price History'));

OR

This can also be accomplished with CSS by setting text-transform to lowercase for the entire element and using the ::first-letter pseudo-element to set the text-transform to uppercase.

.capitalize-first {
  text-transform: lowercase;
}
.capitalize-first::first-letter {
  text-transform: uppercase;
}
<p class="capitalize-first">Download Price History</p>

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading