Javascript capitalise first letter

How to capitalize the first letter of a string in JavaScript

The first thing we want to do is take the string we’re trying to capitalize and separate it into two pieces, the first letter, and everything else. To accomplish this we’ll use an ES6 feature called Array Destructuring (which conveniently works on strings as well).

Just as if we were to destructure the string in the body of the function, we can also do it in the function’s parameter.

const capitalize = ([firstLetter, . restOfWord]) => >;

At this point we have two variables local to our capitalize function — firstLetter and restOfWord . firstLetter is, well, the first letter of the string argument that was passed into capitalize . restOfWord is an array that contains all of the other characters of the argument.

const capitalize = ([firstLetter, . restOfWord]) =>
console.log(firstLetter); // 'h'
console.log(restOfWord); // ["e", "l", "l", "o"]
>;

Now that we’ve separated our string into the first letter and everything else, the next step is to capitalize the first letter. Lucky for us, all JavaScript strings have access to a .toUpperCase method which we can use.

const capitalize = ([firstLetter, . restOfWord]) =>
const capitalizedFirstLetter = firstLetter.toUpperCase();
>;

The final step is to take the capitalized first letter, combine it with the rest of the word, and return the result.

Remember at this point we have two variables, capitalizedFirstLetter which is a string and restOfWord which is an array. If we convert restOfWord back to a string then we can just return the result of adding capitalizedFirstLetter and the string form of restOfWord back together.

To convert an array into a string, we can use the .join method.

const capitalize = ([firstLetter, . restOfWord]) =>
const capitalizedFirstLetter = firstLetter.toUpperCase();
const restOfWordString = restOfWord.join("");
>;

Now that we have the capitalized first letter and the rest of the word as a string, we can add them together and return the result.

const capitalize = ([firstLetter, . restOfWord]) =>
const capitalizedFirstLetter = firstLetter.toUpperCase();
const restOfWordString = restOfWord.join("");
return capitalizedFirstLetter + restOfWordString;
>;

Now to get to our final solution, we can get rid of the variables and use Arrow Function’s implicit return.

const capitalize = ([firstLetter, . restOfWord]) =>
firstLetter.toUpperCase() + restOfWord.join("");

The ES5 solution follows the same logic as the ES6 solution. We first want to separate the first letter from the rest of the word. In ES5, we can grab the first letter by using bracket notation at the 0 index and we can get the rest of the word by using JavaScript’s .slice method.

function capitalize(string)
var firstLetter = string[0];
var restOfWord = string.slice(1); // start at the 1 index
>

Now that we’ve separated the first letter from the rest of the word, we want to capitalize the first letter then combine it with the rest of the word.

function capitalize(string)
var firstLetter = string[0];
var restOfWord = string.slice(1); // start at the 1 index
return firstLetter.toUpperCase() + restOfWord;
>

And finally, to get to our final solution we can get rid of the variable and do everything in line.

function capitalize(string)
return string[0].toUpperCase() + string.slice(1);
>

Avatar for Tyler McGinnis

Tyler McGinnis

CEO of ui.dev. Obsessed with teaching, writing, swimming, biking, and running.

Share this post

Before you leave

I know, another newsletter pitch — but hear me out. Most JavaScript newsletters are terrible. When’s the last time you actually looked forward to getting one? Even worse, when’s the last time you actually read one? We wanted to change that.

We call it Bytes, but others call it their favorite newsletter.

Avatar for @sduduzo_g

This is the first ever newsletter that I open a music playlist for and maximize my browser window just to read it in peace. Kudos to @uidotdev for great weekly content.

Avatar for @flybayer

The Bytes newsletter is a work of art! It’s the only dev newsletter I’m subscribed too. They somehow take semi boring stuff and infuse it with just the right amount of comedy to make you chuckle.

Avatar for @johnhawly

Bytes has been my favorite newsletter since its inception. It’s my favorite thing I look forward to on Mondays. Goes great with a hot cup of coffee!

Avatar for @garrettgreen

I subscribe to A LOT of dev (especially JS/TS/Node) newsletters and Bytes by @uidotdev is always such a welcomed, enjoyable change of pace to most (funny, lighthearted, etc) but still comprehensive/useful.

Avatar for @mhashim6_

Literally the only newsletter I’m waiting for every week.

Avatar for @graysonhicks

Bytes is the developer newsletter I most look forward to each week. Great balance of content and context! Thanks @uidotdev.

Avatar for @mitchellbwright

I know I’ve said it before, but @tylermcginnis doesn’t miss with the Bytes email. If you’re a developer, you really need to subscribe

Avatar for @aspittel

Can I just say that I giggle every time I get the @uidotdev email each week? You should definitely subscribe.

Avatar for @thefinnomenon

Every JavaScript programmer should be subscribed to the newsletter from @uidotdev. Not only do they manage to succinctly cover the hot news in the JavaScript world for the week but it they manage to add a refreshing humor to it all.

Источник

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.

Источник

Читайте также:  Python создать файл docx
Оцените статью