Skip to content
the poor coder

Javascript Capitalize First Letter

Poor Man
Published
Reading time
1 min read

If you want to capitalize the first letter of a string in JavaScript, you have a few different options. The simplest approach is to use the built-in String.prototype.toUpperCase() function. You can pass a single character string to this function, and it will return the same single character string, but with the first letter capitalized.

Text

let str = "hello world";
let capitalizedStr = str.charAt(0).toUpperCase() + str.substr(1);
// Output: Hello World

Another way to capitalize the first letter of a string is to use the Array.prototype.shift() and Array.prototype.join() functions. You can pass a single character string to the Array.prototype.shift() function and it will return the same single character string, but with the first letter capitalized. Then you can pass the result of the shift function to the Array.prototype.join() function, which will join all the characters together into a single string.

Text

let str = "hello world";
let arr = str.split(""); // split string into array
let capitalizedArr = arr.shift().toUpperCase() + arr.join("");
 
// Output: Hello World

Finally, you can also use the RegExp.prototype.replace() function to capitalize the first letter of a string. This approach is a bit more complicated, but it can be useful if you need to do something more complicated than simply capitalizing the first letter.

Text

let str = "hello world";
let capitalizedStr = str.replace(/^\w/, c => c.toUpperCase());
 
// Output: Hello World 

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC