C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Example: In case you are wondering, here is how you can use toUpperCase and toLowerCase.
Original: The original string we call these methods on is left unchanged and be used again.
Here: We take a string in mixed case (title case) and transform it to uppercase and then to all lowercase.
StringsJavaScript program that uses toUpperCase, toLowerCase
var color = "Blue";
// Create a copy of the string and uppercase it.
// ... The original is left alone.
var upper = color.toUpperCase();
console.log("BEFORE: " + color);
console.log("AFTER (UPPER): " + upper);
// Lowercase a string.
var lower = upper.toLowerCase();
console.log("BEFORE: " + upper);
console.log("AFTER (LOWER): " + lower);
Output
BEFORE: Blue
AFTER (UPPER): BLUE
BEFORE: BLUE
AFTER (LOWER): blue
Tip: This method works well on strings of 1 character or more. And it can be placed in a function for easier reuse.
JavaScript program that uppercases first letter
var animal = "cat";
// Uppercase first letter in a string.
var uppercase = animal[0].toUpperCase() + animal.substring(1);
console.log("RESULT: " + uppercase);
Output
RESULT: Cat
Tip: This function handles zero-length strings. For strings with an initial letter already uppercased, it changes nothing.
JavaScript program that uses function
function upperFirst(value) {
if (value.length >= 1) {
return value[0].toUpperCase() + value.substring(1);
}
return value;
}
// Test upperFirst on many strings.
var values = ["cat", "", "c", "dog", "BIRD"];
for (var i = 0; i < values.length; i++) {
console.log("STRING: " + values[i]);
console.log("UPPERFIRST: " + upperFirst(values[i]));
}
Output
STRING: cat
UPPERFIRST: Cat
STRING:
UPPERFIRST:
STRING: c
UPPERFIRST: C
STRING: dog
UPPERFIRST: Dog
STRING: BIRD
UPPERFIRST: BIRD
And: On the first character, or a lowercase-range ASCII letter following a space, we append the uppercase form of the letter.
For other chars: We just append the original character. The result is built up as we go a long, and returned in the final line.
JavaScript program that uppercases all words in string
function uppercaseAllWords(value) {
// Build up result.
var result = "";
// Loop over string indexes.
for (var i = 0; i < value.length; i++) {
// Get char code at this index.
var code = value.charCodeAt(i);
// For first character, or a lowercase range char following a space.
// ... The value 97 means lowercase A, 122 means lowercase Z.
if (i === 0 ||
value[i - 1] === " " &&
code >= 97 &&
code <= 122) {
// Convert from lowercase to uppercase by subtracting 32.
// ... This uses ASCII values.
result += String.fromCharCode(code - 32);
}
else {
result += value[i];
}
}
return result;
}
console.log("RESULT: " + uppercaseAllWords("welcome visitors, enjoy your stay"));
Output
RESULT: Welcome Visitors, Enjoy Your Stay