First letter capitalized javascript

String: Capitalize First Letter

In JavaScript, and programming in general, one can solve the same problem in various ways. When it comes to first letter capitalization, JavaScript offers a few ways to implement it in the console output.

Method toUpperCase() and slice()

This function is applied to a string and changes all letters of it to uppercase. You might stipulate that you only need a single letter to remain capitalized. This function is still suitable for such purposes. It is achieved by combining this function with other JavaScript functionality. As of now, the syntax of the toUpperCase() function looks like this:

The return of this function is a capitalized string. You should also be aware that this function works better when used in aggregate with the slice() function. More precisely, it applies to a string, allowing one to slice it according to the passed parameters. The syntax of this function is as follows:

Please note that start and end parameters are essential to specify where the slicing position begins and finishes. In other words, start signals the beginning of slicing, and its indexing starts from 0. As for the end parameter, it specifies the exact position from where to stop slicing. Although it’s an optional value, it selects all characters from the start parameter if you ignore it.

So, how does the combination of these two functions allow capitalizing the first letter? Check the following example:

function capitalize(str) < return `$0).toUpperCase()>$1)>`; > console.log(capitalize('test')); // Output: Test

Still, combining the toUpperCase() and slice() seems to be the most straightforward and accessible capitalization approach in JavaScript.

Function charAt()

You can also combine three different functions to capitalize the first letter in JavaScript. As a whole, charAt() function is used to return the character to a determined position in a string. Try working with the following code:

const str = 'example'; const str2 = str.charAt(0); console.log(str2); // Output: e

In this example, the return you see in a console is » e .» But what if you mix this function with replace() and experiment with a console for a while? Try combining the following examples in your compiler:

const str = "example"; const firstChar = str.charAt(0); const capitalized = str.replace(firstChar, firstChar.toUpperCase()); console.log(capitalized); // Output: "Example" // Alternative one-line solution with regex const capitalized2 = str.replace(/^(.)/, (match) => match.toUpperCase()); console.log(capitalized2); // Output: "Example"

In the first case, we use the word example and get the output of Example as a return. The same goes for example , which capitalizes only E in this input. It works because the charAt() function returns the character at a given position, while toUpperCase() converts all the characters of an input string into upper cases.

But why do we get only the first letter capitalized? If we provide a substring instead of a regex pattern as the first argument, only the first occurrence will be replaced. In the second example, we use a regular expression pattern and match the first character, and then we transform it using the callback function.

Читайте также:  outline-style

Capitalizing the first letter in each word

What if you need to capitalize the first letter of each word in your sentence? In this case, you’ll need to split the words from their respective strings and store them in an array.

Your next step is to use the mentioned combination of functions to each array and join all the array elements back. As a result, you’ll get a string back and get the expected return in your console. Consider this as an example:

const str = 'learning javascript is actually fun and not that complicated'; const arr = str.split(' '); for (let i = 0; i < arr.length; i++) < arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1); > const str2 = arr.join(' '); console.log(str2);

In this prompt, we entered the following sentence: «learning javascript is actually fun and not that complicated». Not only do we really think so, but we can also explain how the use of an array works in this situation.

Firstly, you split the sentence string into an array of strings, only to loop through each element to capitalize the first letter. Secondly, you join all the array elements back into a string, using a blank space as a separator between them. Voila, your return will look like this:

Learning Javascript Is Actually Fun And Not That Complicated

Method map()

Because JavaScript has a comprehensive functionality, you can also capitalize the first letter using the map method. Check out how it works before we elaborate on its nuances:

function capitalize(. words) < return words.map((word) => `$0, 1).toUpperCase()>$1)>`).join(' '); > console.log(capitalize('some', 'kind', 'of', 'lower-cased', 'words', '. ')); // Output: Some Kind Of Lower-cased Words . 

With this method, you include the function capitalize(), and use the … (rest operator) and toUpperCase() function. There you use the map() method, which creates a new array from provided arguments, after remapping, you should use join to unite the separate words into one string .

Читайте также:  Окончание чисел в питоне

Alternatives

The examples mentioned above are the more accessible methods to capitalize letters. You can also experiment using other methods, which are best known as using RegEx or rest . Since they are more complicated and less readable, they are rarely used for upper cases.

Instead, most developers rely on combining charAt() , toUpperCase() and slice() , replace() functions since they offer the most variability.

Источник

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.

Читайте также:  Чем можно открыть файл html

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

Источник

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 

Источник

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