JavaScript provides two methods to convert a string to all uppercase or all lowercase, so that "hello" can be changed to "HELLO", or "NOT" can be changed to "not". You may ask, why? Converts the letters in a string to the same case, which can make comparing two strings easier. For example, suppose you create a quiz program, and a question is "Who was the first American to win the Tour De France?" You might use code similar to the following to check the answers of the participating participants:
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 will happen if the person taking the question enters Greg Lemond? The condition looks something like this: 'Greg Lemond'=='Greg LeMond'. Since JavaScript is case-sensitive, the lowercase 'm' in Lemond will not match the 'M' in LeMond. Therefore, participants may get incorrect answers. If the participant presses the Caps key and enters GREG LEMOND, the same result will be obtained.
To solve this puzzle, we can convert both strings to the same case and then compare them:
if(response.toUpperCase()==correctAnswer.toUpperCase()){ //correct }else{ //incorrect }
In this example, the conditional converts both the participant's answer and the correct answer to uppercase letters, so 'Greg Lemond' becomes 'GREG LEMOND' and 'Greg LeMond' becomes 'GREG LEMOND'.
To get an all-lowercase string, use the toLowerCase() method like this:
var answer='Greg LeMond'; alert(answer.toLowerCase());//'greg lemond'
Note that none of these methods actually change the string actually stored in the variable, they just return the string in all uppercase or all lowercase. So, in the above example, even after the prompt appears, the answer still contains 'Greg LeMond' (they return some other value).
toLowerCase() and toUpperCase() are two classic methods, borrowed from the method of the same name in java.lang.String. The toLocaleLowerCase() and toLocaleUpper() methods are implementations for specific regions. For some regions, the region-specific method yields the same results as the universal method, but a few languages apply special rules for Unicode case conversion. In this case, the region-specific method must be used to ensure 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 like calling toLocaleLowerCase() and toLowerCase() both return "hello world". Generally speaking, if you don't know which language environment your code will run in, it is safer to use a region-specific approach.
The above is the entire content of this article, I hope you all like it.