Javascript Capitalize First Letter

Javascript Capitalize First Letter

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.


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.


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.


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

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe