string uppercase
Understanding String Uppercase
String uppercase is a method used to convert all characters in a given string to uppercase letters. This can be useful in various scenarios where you need to manipulate strings or compare them in a case-insensitive manner.
Using the toUpperCase() Method
The most common way to perform string uppercase in JavaScript is by using the toUpperCase() method. This method belongs to the String object and converts all lowercase characters in a string to uppercase.
let str = "hello world";
let upperStr = str.toUpperCase();
console.log(upperStr);
// Output: "HELLO WORLD"
Using CSS Text Transform Property
You can also convert strings to uppercase using CSS text-transform property. This can be useful when you want to style text on a webpage.
.uppercase {
text-transform: uppercase;
}
Using Regular Expressions
Another way to perform string uppercase is by using regular expressions. This method involves replacing lowercase characters with their uppercase counterparts.
let str = "hello world";
let upperStr = str.replace(/[a-z]/g, function(char) {
return char.toUpperCase();
});
console.log(upperStr);
// Output: "HELLO WORLD"
Using ASCII Codes
You can also perform string uppercase by converting lowercase characters to their ASCII codes and subtracting 32 from them. This will give you the corresponding uppercase ASCII code, which can then be converted back to a character using the String.fromCharCode() method.
let str = "hello world";
let upperStr = "";
for(let i=0; i<str.length; i++) {
let charCode = str.charCodeAt(i);
if(charCode>=97 && charCode<=122) { // Check if lowercase letter
charCode -= 32; // Convert to uppercase ASCII code
}
upperStr += String.fromCharCode(charCode); // Convert back to character
}
console.log(upperStr);
// Output: "HELLO WORLD"
These are some of the ways to perform string uppercase in JavaScript. Choose the method that suits your needs and use it to manipulate strings in your code.