JavaScript changes the case of the string

  • 2020-06-07 03:59:55
  • OfStack

JavaScript provides two methods for converting strings to all uppercase or all lowercase, so that you can change "hello" to "HELLO" or "NOT" to "not". Why, you may ask? Converts letters in a string to the same case, which makes it easier to compare two strings. For example, suppose you create a program and the question is "Who was the first American to the Tour France?". You might check the answers of the participants with a code like the following:


var correctAnswer='Greg LeMond' ; 
var response=prompt ( 'Who was the first American to win the Tour De8
France?' . '' ); 
if ( response==correctAnswer ) {
//correct
}else{
//incorrect
}

The answer is Greg LeMond, but what if the participant typed Greg Lemond? The condition looks something like this: 'Greg Lemond'=='Greg LeMond'. Because JavaScript is case sensitive, the lowercase 'm' in Lemond does not match the 'M' in LeMond, so participants may get the answer wrong. The same result is obtained if the respondent presses the Caps key and enters GREG LEMOND.

To solve this puzzle, we can convert both strings to the same case and then compare them:


if ( response.toUpperCase (a) ==correctAnswer.toUpperCase ()) {
//correct
}else{
//incorrect
}

In this example, conditional statements convert both the respondent's answer and the correct answer to capital letters, so 'Greg Lemond' becomes 'GREG LEMOND' and 'Greg LeMond' becomes 'GREG LEMOND'.

To get all lowercase strings, use the toLowerCase () method as follows:


var answer='Greg LeMond' ; 
alert ( answer.toLowerCase ()); //'greg lemond'

Note that none of these methods really change the actual string stored in the variable, they just return the string in all uppercase or all lowercase. Thus, in the above example, answer still contains 'Greg LeMond' (they return some other value) even after the prompt appears.

toLowerCase() and toUpperCase() are two classic methods, borrowed from the method of the same name in ES65en.lang.String. The toLocaleLowerCase() and toLocaleUpper() methods are locale-specific implementations. For some locales, the locale-specific method will yield the same results as the generic method, but a few languages will apply special rules for Unicode case conversion, and the locale-specific method must be used to ensure the correct conversion.

Here are a few examples:


var sv="hello world";
alert(sv.toLocaleUpperCase());//"HELLO WORLD"
alert(sv.toUpperCase());//"HELLO WORLD"
alert(sv.toLocaleLowerCase());//"hello world"
alert(sv.toLowerCase());// " hello world " 

The toLocaleUpperCase() and toUpperCase() used in the above code both return "HELLO WORLD", just as calls to toLocaleLowerCase() and toLowerCase() both return "hello world" 1. In general, it is safer to use a locale-specific approach without knowing which locale your code will run in.

This is the end of this article, I hope you enjoy it.


Related articles: