How do I make the first letter of a string uppercase in JavaScript?

Programise
1 min readJan 16, 2023

--

String uppercase in javascript

In JavaScript, you can make the first letter of a string uppercase using the .replace() method and a regular expression. Here's an example:

let originalString = "hello world";
let newString = originalString.replace(/^\w/, c => c.toUpperCase());
console.log(newString); // "Hello world"

In this example, originalString.replace(/^\w/, c => c.toUpperCase()) replaces the first letter of the string with its uppercase version. The regular expression /^\w/ matches the first letter of the string, and the c => c.toUpperCase() function is used to convert that letter to uppercase.

Alternatively you can use the .slice() method to select the first character and then concatenate it with the rest of the string after making it uppercase by using .toUpperCase() method. Here's an example:

let originalString = "hello world";
let newString = originalString.charAt(0).toUpperCase() + originalString.slice(1);
console.log(newString); // "Hello world"

Both the above examples will give you the same result, with the first letter in uppercase and the rest of the string in lowercase.

--

--

No responses yet