Introduction

In JavaScript, there are several ways to convert a string to uppercase. In this tutorial, we will explore two commonly used methods: the toUpperCase() method and the toLocaleUpperCase() method.

Using the toUpperCase() Method

The toUpperCase() method is used to convert a string to uppercase in JavaScript. It creates a new string with all the characters of the original string converted to uppercase. Here’s an example:

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

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

In this example, the toUpperCase() method is called on the str variable, which contains the string ““hello world””. The resulting uppercase string is stored in the uppercaseStr variable and then logged to the console.

Using the toLocaleUpperCase() Method

The toLocaleUpperCase() method is similar to the toUpperCase() method, but it also takes into account the current locale of the string. This can be useful when dealing with specific characters that have different uppercase forms based on the locale. Here’s an example:

let str = ""café"";
let uppercaseStr = str.toLocaleUpperCase();

console.log(uppercaseStr); // ""CAFÉ""

In this example, the toLocaleUpperCase() method is called on the str variable, which contains the string ““café””. The resulting uppercase string is stored in the uppercaseStr variable and then logged to the console. Notice that the character ““é”” is correctly converted to its uppercase form ““É”” based on the current locale.

Conclusion

Converting a string to uppercase in JavaScript is easy and can be done using the toUpperCase() method or the toLocaleUpperCase() method. The toUpperCase() method is more straightforward and converts all characters to uppercase, while the toLocaleUpperCase() method considers the current locale for accurate uppercase conversion. Choose the method that best suits your needs.

I hope you found this tutorial helpful!