How do you convert a string to uppercase in JavaScript?

In JavaScript, you can convert a string to uppercase using several methods. In this article, we will cover the following techniques:

Let’s dive into each method in detail:

Using the toUpperCase() Method:

The toUpperCase() method is a built-in method in JavaScript that converts a string to uppercase. The method returns a new string with all the characters of the original string converted to uppercase.

Here is an example:

let str = "hello, world!";
let uppercaseStr = str.toUpperCase();

console.log(uppercaseStr); // "HELLO, WORLD!"

In this example, we declare a variable str and assign it a string value of "hello, world!". We then call the toUpperCase() method on the str variable and assign the returned value to a new variable uppercaseStr. Finally, we log the value of uppercaseStr to the console.

Using the toLocaleUpperCase() Method:

The toLocaleUpperCase() method is similar to the toUpperCase() method. However, the toLocaleUpperCase() method is more flexible because it takes into account the user’s locale.

Here is an example:

let str = "i love programming";
let uppercaseStr = str.toLocaleUpperCase("en-US");

console.log(uppercaseStr); // "I LOVE PROGRAMMING"

In this example, we declare a variable str and assign it a string value of "i love programming". We then call the toLocaleUpperCase() method on the str variable and pass in the "en-US" locale as a parameter. The method returns a new string with all the characters of the original string converted to uppercase, taking into account the "en-US" locale. Finally, we log the value of uppercaseStr to the console.

Using the String.prototype.replace() Method with a Regular Expression:

The String.prototype.replace() method is a built-in method in JavaScript that replaces a specified value in a string with another value. We can use this method to convert a string to uppercase by replacing all lowercase characters with their uppercase counterparts.

Here is an example:

let str = "hello, world!";
let uppercaseStr = str.replace(/[a-z]/g, function (match) {
  return match.toUpperCase();
});

console.log(uppercaseStr); // "HELLO, WORLD!"

In this example, we declare a variable str and assign it a string value of "hello, world!". We then call the replace() method on the str variable and pass in a regular expression as the first parameter. The regular expression matches all lowercase characters in the string. We also pass in a function as the second parameter, which is called for each match and returns the uppercase version of the match. Finally, we assign the returned value to a new variable uppercaseStr and log its value to the console.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: