Home » Blog » Convert a String to Upper Case in JavaScript

Convert a String to Upper Case in JavaScript

Learn how to capitalize a string using JavaScript's "toUpperCase" built-in method.

As a developer, you may want to uppercase a string or capitalize the first letter. I’ll show you how to do it using JavaScript.

If you need it later, I also write another article about how to convert a string to lower case in JavaScript.

A built-in method to return a string to upper case in JS (toUpperCase)

In JavaScript, all strings have a built-in function to convert a string to uppercase.

This function is toUpperCase() and it don’t take any parameters. Similar to toLowerCase(), it will not update your string but return an updated version.

An example of how to uppercase in JavaScript

Let me show you a quick example with a lowercase string.

const lastName = 'thomas'

// Convert the lowercase string to uppercase
console.log(lastName.toUpperCase())

// Output: "THOMAS"

As mentioned previously, this function will not modify the original string. If you want to save your upper case result, you’ll need to create a new variable.

Here’s how you can do it!

const lastName = 'ThOmAs'
const upperCaseLastName = lastName.toUpperCase()

console.log(lastName)
// Output: "ThOmAs"

console.log(upperCaseLastName)
// Output: "THOMAS"

As you can see, the first variable stays unchanged.

How to uppercase the first letter of a string in JavaScript

Let’s say that you want to convert a customer’s first name with an uppercase first letter.

To do so, you will need different built-in methods to capitalize the first letter and re-create a new string.

Here they are:

Now, let’s put it into practice!

const firstName = 'gael'

// We create a new variable = 'g'.toUpperCase() + 'ael'
const capitalizedFirstName =
  firstName.charAt(0).toUpperCase() + firstName.slice(1)

console.log(capitalizedFirstName)
// Output: "Gael"

If you want to move a bit further, you can also create a generic function to uppercase the first letter.

const capitalizeFirstLetter = (value) => {
  return value.charAt(0).toUpperCase() + value.slice(1)
}

const capitalizedFirstName = capitalizeFirstLetter('gael')

console.log(capitalizedFirstName)
// Output: "Gael"

Thanks for reading. Let’s connect!

➡️ I help you grow into Web Development, and I share my journey as a Nomad Software Engineer. Join me on Twitter for more. 🚀🎒

Gaël Thomas

🚀 Help you grow into Web Development 👨‍💻 Share about my journey as Nomad Software Engineer 🧰 Into JavaScript, TypeScript, Node, and React

Post navigation