Clue Mediator

Capitalize the first letter of a string using JavaScript

๐Ÿ“…February 18, 2022
๐Ÿ—JavaScript

In this JavaScript article, we will show you how to capitalize the first letter of a string using JavaScript. There are many ways to uppercase the first letter of a string in JavaScript but we will look at two of them.

Checkout more articles on JavaScript

Methods to capitalize the first letter of a string

  1. Using charAt() and slice()
  2. Using regular expression

1. Using charAt() and slice()

In the first method, we will use the following functions and concat a string.

  • `charAt()` - This function returns the character at a given position in the string.
  • `slice()` - This function extracts a section of a string and returns it as a new string, without modifying the original string.
const str = "cluemediator";
const output = str.charAt(0).toUpperCase() + str.slice(1);
console.log(output);
// Output: Cluemediator

You can also use the following code.

const str = "cluemediator";
const output = str[0].toUpperCase() + str.slice(1);
console.log(output);
// Output: Cluemediator

2. Using regular expression

Letโ€™s use the Regular Expression to make the first letter of a string in uppercase.

const str = "cluemediator";
const output = str.replace(/^./, str[0].toUpperCase());
console.log(output);
// Output: Cluemediator

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚