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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28188{{"`Capitalize First Letter in JavaScript`"}} javascript/data_types -.-> lab-28188{{"`Capitalize First Letter in JavaScript`"}} javascript/arith_ops -.-> lab-28188{{"`Capitalize First Letter in JavaScript`"}} javascript/comp_ops -.-> lab-28188{{"`Capitalize First Letter in JavaScript`"}} javascript/spread_rest -.-> lab-28188{{"`Capitalize First Letter in JavaScript`"}} end

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.

Other JavaScript Tutorials you may like