Capitalize First Letter in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a JavaScript function called capitalize that capitalizes the first letter of a string. The function uses array destructuring and String.prototype.toUpperCase() to achieve the desired result. We will also see how to use the lowerRest argument to convert the rest of the string to lowercase if needed.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

JavaScript Function to Capitalize First Letter of a String

To capitalize the first letter of a string in JavaScript, use the following function:

const capitalize = (str, lowerRest = false) => {
  const [first, ...rest] = str;
  return (
    first.toUpperCase() +
    (lowerRest ? rest.join("").toLowerCase() : rest.join(""))
  );
};

This function uses array destructuring and String.prototype.toUpperCase() to capitalize the first letter of the string. The lowerRest argument is optional and can be set to true to convert the rest of the string to lowercase.

Here is an example of how to use this function:

capitalize("fooBar"); // 'FooBar'
capitalize("fooBar", true); // 'Foobar'

Summary

Congratulations! You have completed the Capitalize String lab. You can practice more labs in LabEx to improve your skills.