- JavaScript: Capitalize the first letter
- Table of Contents
- Capitalize the first letter of a string
- charAt():
- toUpperCase()
- slice
- Capitalize the first letter of each word in a string
- How to Capitalize the First Letter of Each Word in JavaScript – a JS Uppercase Tutorial
- Capitalize the first letter of a word
- How to capitalize the first letter
- Let’s recap
- Capitalize the first letter of each word from a string
- Split it into words
- Iterate over each word
- Join the words
- Other methods
- Conclusion
- String.prototype.toUpperCase()
- Try it
- Syntax
- Return value
- Description
- Examples
- Basic usage
- Conversion of non-string this values to strings
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to uppercase the first letter of a string in JavaScript
JavaScript: Capitalize the first letter
In this tutorial, we shall look at capitalizing the first letter of a string in JavaScript followed by learning how we can capitalize the first letter of each word in a string.
Table of Contents
Capitalize the first letter of a string
To achieve the capitalization of the first letter of a given string in JavaScript, we would use three functions.
charAt():
The charAt() function returns the character at a given position in a string.
const str = 'flexiple'; const str2 = str.charAt(0); console.log(str2); //Output: f
toUpperCase()
The toUpperCase() function converts all the characters of an input string to uppercase
const str = 'flexiple'; const str2 = str.toUpperCase(); console.log(str2); //Output: FLEXIPLE
In the above example, we see that using the toUpperCase() function on the string converted all the characters of the input string to capital letters.
But this is not what we desire to achieve. To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.
slice
This function slices a given string from a specified “start” position until the specified “end” position.
const str = 'flexiple'; const str2 = str.slice(1); console.log(str2); //Output: lexiple
Now let us use all the three functions together to capitalize the first word of an input string.
const str = 'flexiple'; const str2 = str.charAt(0).toUpperCase() + str.slice(1); console.log(str2); //Output: Flexiple const str = 'abc efg'; const str2 = str.charAt(0).toUpperCase() + str.slice(1); console.log(str2); //Output: Abc efg
As you can see from the above outputs that we have capitalized the first letter of the input string. Now what if we want to capitalize the first letters of all the words in a string? Let’s see how we can achieve this as well.
Capitalize the first letter of each word in a string
To achieve this, we split the words from the string and store them in an array, and then use the above concept on each element of the array and join all the array elements together to get the string back. Let us take a look at this using an example
const str = 'i have learned something new today'; //split the above string into an array of strings //whenever a blank space is encountered const arr = str.split(" "); //loop through each element of the array and capitalize the first letter. for (var i = 0; i < arr.length; i++) < arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1); >//Join all the elements of the array back into a string //using a blankspace as a separator const str2 = arr.join(" "); console.log(str2); //Outptut: I Have Learned Something New Today
How to Capitalize the First Letter of Each Word in JavaScript – a JS Uppercase Tutorial
Catalin Pit
In this article, you are going to learn how to capitalize the first letter of any word in JavaScript. After that, you are going to capitalize the first letter of all words from a sentence.
The beautiful thing about programming is that there is no one universal solution to solve a problem. Therefore, in this article you are going to see multiple ways of solving the same problem.
Capitalize the first letter of a word
First of all, let’s start with capitalizing the first letter of a single word. After you learn how to do this, we’ll proceed to the next level – doing it on every word from a sentence. Here is an example:
const publication = "freeCodeCamp";
In JavaScript, we start counting from 0. For instance, if we have an array, the first position is 0, not 1.
Also, we can access each letter from a String in the same way that we access an element from an array. For instance, the first letter from the word «freeCodeCamp» is at position 0.
This means that we can get the letter f from freeCodeCamp by doing publication[0] .
In the same way, you can access other letters from the word. You can replace «0» with any number, as long as you do not exceed the word length. By exceeding the word length, I mean trying to do something like publication[25 , which throws an error because there are only twelve letters in the word «freeCodeCamp».
How to capitalize the first letter
Now that we know how to access a letter from a word, let’s capitalize it.
In JavaScript, we have a method called toUpperCase() , which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase.
const publication = "freeCodeCamp"; publication[0].toUpperCase();
Running the above code, you are going to get a capital F instead of f. To get the whole word back, we can do this:
const publication = "freeCodeCamp"; publication[0].toUpperCase() + publication.substring(1);
Now it concatenates «F» with «reeCodeCamp», which means we get back the word «FreeCodeCamp». That is all!
Let’s recap
To be sure things are clear, let’s recap what we’ve learnt so far:
- In JavaScript, counting starts from 0.
- We can access a letter from a string in the same way we access an element from an array — e.g. string[index] .
- Do not use an index that exceeds the string length (use the length method — string.length — to find the range you can use).
- Use the built-in method toUpperCase() on the letter you want to transform to uppercase.
Capitalize the first letter of each word from a string
The next step is to take a sentence and capitalize every word from that sentence. Let’s take the following sentence:
const mySentence = "freeCodeCamp is an awesome resource";
Split it into words
We have to capitalize the first letter from each word from the sentence freeCodeCamp is an awesome resource .
The first step we take is to split the sentence into an array of words. Why? So we can manipulate each word individually. We can do that as follows:
const mySentence = "freeCodeCamp is an awesome resource"; const words = mySentence.split(" ");
Iterate over each word
After we run the above code, the variable words is assigned an array with each word from the sentence. The array is as follows [«freeCodeCamp», «is», «an», «awesome», «resource»] .
const mySentence = "freeCodeCamp is an awesome resource"; const words = mySentence.split(" "); for (let i = 0; i
Now the next step is to loop over the array of words and capitalize the first letter of each word.
In the above code, every word is taken separately. Then it capitalizes the first letter, and in the end, it concatenates the capitalized first letter with the rest of the string.
Join the words
What is the above code doing? It iterates over each word, and it replaces it with the uppercase of the first letter + the rest of the string.
If we take «freeCodeCamp» as an example, it looks like this freeCodeCamp = F + reeCodeCamp .
After it iterates over all the words, the words array is [«FreeCodeCamp», «Is», «An», «Awesome», «Resource»] . However, we have an array, not a string, which is not what we want.
The last step is to join all the words to form a sentence. So, how do we do that?
In JavaScript, we have a method called join , which we can use to return an array as a string. The method takes a separator as an argument. That is, we specify what to add between words, for example a space.
const mySentence = "freeCodeCamp is an awesome resource"; const words = mySentence.split(" "); for (let i = 0; i < words.length; i++) < words[i] = words[i][0].toUpperCase() + words[i].substr(1); >words.join(" ");
In the above code snippet, we can see the join method in action. We call it on the words array, and we specify the separator, which in our case is a space.
Therefore, [«FreeCodeCamp», «Is», «An», «Awesome», «Resource»] becomes FreeCodeCamp Is An Awesome Resource .
Other methods
In programming, usually, there are multiple ways of solving the same problem. So let’s see another approach.
const mySentence = "freeCodeCamp is an awesome resource"; const words = mySentence.split(" "); words.map((word) => < return word[0].toUpperCase() + word.substring(1); >).join(" ");
What is the difference between the above solution and the initial solution? The two solutions are very similar, the difference being that in the second solution we are using the map function, whereas in the first solution we used a for loop .
Let’s go even further, and try to do a one-liner. Be aware! One line solutions might look cool, but in the real world they are rarely used because it is challenging to understand them. Code readability always comes first.
const mySentence = "freeCodeCamp is an awesome resource"; const finalSentence = mySentence.replace(/(^\w)|(\s+\w)/g, letter => letter.toUpperCase());
The above code uses RegEx to transform the letters. The RegEx might look confusing, so let me explain what happens:
- ^ matches the beginning of the string.
- \w matches any word character.
- takes only the first character.
- Thus, ^\w matches the first letter of the word.
- | works like the boolean OR . It matches the expression after and before the | .
- \s+ matches any amount of whitespace between the words (for example spaces, tabs, or line breaks).
Thus, with one line, we accomplished the same thing we accomplished in the above solutions. If you want to play around with the RegEx and to learn more, you can use this website.
Conclusion
Congratulations, you learnt a new thing today! To recap, in this article, you learnt how to:
- access the characters from a string
- capitalize the first letter of a word
- split a string in an array of words
- join back the words from an array to form a string
- use RegEx to accomplish the same task
Thanks for reading! If you want to keep in touch, let’s connect on Twitter @catalinmpit. I also publish articles regularly on my blog catalins.tech if you want to read more content from me.
String.prototype.toUpperCase()
The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn’t one).
Try it
Syntax
Return value
A new string representing the calling string converted to upper case.
Description
The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.
Examples
Basic usage
.log("alphabet".toUpperCase()); // 'ALPHABET'
Conversion of non-string this values to strings
This method will convert any non-string value to a string, when you set its this to a value that is not a string:
const a = String.prototype.toUpperCase.call( toString() return "abcdef"; >, >); const b = String.prototype.toUpperCase.call(true); // prints out 'ABCDEF TRUE'. console.log(a, b);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 6, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How to uppercase the first letter of a string in JavaScript
Capitalizing a string means uppercasing the first letter of it. It’s one of the most common operations with strings in JavaScript: uppercase its first letter, and leave the rest of the string as-is.
The best way to make the first character uppercase is through a combination of two functions.
One function is used to to uppercases the first letter, and the second function slices the string and returns it starting from the second character.
const name = 'flavio' const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1)
You can extract that method of capitalizing a string to a function, which also checks if the passed parameter is a string, and returns an empty string if not:
const capitalize = (s) => if (typeof s !== 'string') return '' return s.charAt(0).toUpperCase() + s.slice(1) > capitalize('flavio') //'Flavio' capitalize('f') //'F' capitalize(0) //'' capitalize(<>) //''
Instead of using s.charAt(0) you could also use string indexing (not supported in older IE versions): s[0] .
Some solutions online to do the same capilization by having the first letter uppercase advocate for adding the function to the String prototype:
String.prototype.capitalize = function() return this.charAt(0).toUpperCase() + this.slice(1) >
(we use a regular function to make use of this — arrow functions would fail in this case, as this in arrow functions does not reference the current object)
This solution is not ideal, because editing the prototype is not generally recommended, and it’s a much slower solution than having an independent function.
Don’t forget that if you just want to capitalize (having the first letter uppercase) for presentational purposes on a Web Page, CSS might be a better solution, just add a capitalize class to your HTML paragraph and use:
p.capitalize text-transform: capitalize; >