Javascript uppercase first letters

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.

Читайте также:  Графический редактор для html

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

Catalin Pit

How to Capitalize the First Letter of Each Word in JavaScript – a JS Uppercase Tutorial

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.

Источник

JavaScript Capitalize First Letter – How to Uppercase the First Letter in a Word with JS

Dillion Megida

Dillion Megida

JavaScript Capitalize First Letter – How to Uppercase the First Letter in a Word with JS

When you’re coding, there are many ways to capitalize the first letter of a word. You can use CSS as well as some JavaScript methods.

In this article, I will show you one approach to achieve this.

To capitalize the first letter of a word with JS, you need to understand three string methods: charAt, slice, and toUpperCase.

The charAt JavaScript string method

You use this method to retrieve the character at a specified position in a string. Using this method, we can retrieve the first letter in a word:

const word = "freecodecamp" const firstLetter = word.charAt(0) // f 

The slice JavaScript string method

You use this method to cut out a substring from an entire string. We will use this method to cut out the remaining part of a word (excluding the first letter):

const word = "freecodecamp" const remainingLetters = word.substring(1) // reecodecamp 

The toUpperCase JavaScript string method

toUpperCase is a string method that returns the uppercased version of a specified string. We will use this to capitalize the first letter:

const firstLetter = "f" const firstLetterCap = firstLetter.toUpperCase() // F 

How to capitalize the first letter of a word in JavaScript

Using the three string methods above, we will get the first character of the word, capitalize it, then concatenate it with the remaining sliced part.

This approach will result in a new word that has the first letter capitalized.

const word = "freecodecamp" const firstLetter = word.charAt(0) const firstLetterCap = firstLetter.toUpperCase() const remainingLetters = word.slice(1) const capitalizedWord = firstLetterCap + remainingLetters // Freecodecamp // F is capitalized 

The short version for the code above is:

const word = "freecodecamp" const capitalized = word.charAt(0).toUpperCase() + word.slice(1) // Freecodecamp // F is capitalized 

Thank you for reading, and happy coding!

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Оцените статью