This article mainly introduces how to determine whether two strings are equal in JavaScript, which is the basic knowledge in JS learning, for more information, see convert all user input values to uppercase (or lowercase) and then compare them:
var name = document.form1.txtUserName.value.toLowerCase(); if(name == "urname") { // statements go here. }
JavaScript has two equal operators. One is completely backward compatible, the standard "=". If the two operand types are inconsistent, it will automatically convert the type of the operand in some cases. Consider the following assignment statement:
var strA = "i love you!"; var strB = new String("i love you!");
These two variables contain the same character sequence, but their data types are different. The former is string, and the latter is object. When the "=" operator is used, JavaScript will try to evaluate various types of values, to check whether the two are equal under certain circumstances. Therefore, the following expression returns true: strA = strB.
The second operator is "strict" "=". It is not so tolerant in value evaluation and does not perform type conversion. Therefore, the value of the expression strA === strB is false, although the two variables hold the same value.
Sometimes the logic of the Code requires you to determine whether two values are not equal. Here there are two options :"! = "And strict "! = ", Their relationships are similar to" = "and" = ".
Discussion:
"=" And "! = "When you evaluate the value, you will try to find the matching of the value, but you may still want to perform explicit type conversion before comparison to" help "them complete their work. For example, if you want to determine whether a user's input value (string) is equal to a number, you can enable "=" to help you complete type conversion:
if(document.form1.txtAge.value == someNumericVar) { ... }
Conversion can also be performed in advance:
if(parseInt(document.form1.txtAge.value) == someNumericVar) { ... }
If you are more accustomed to strong programming languages (such as C # and Java), you can continue your habits (type conversion) Here, which will also enhance the readability of the program.
Note that you need to set the computer region. If you use "<" and ">" to compare strings, JavaScript compares them as Unicode, but obviously, people do not read text as Unicode when browsing the Web page. For example, in Spanish, "ch" is traditionally sorted as a character between "c" and "d. LocaleCompare () provides a way to help you set character sorting rules in the default region.
Var strings; // array of strings to be sorted. Assume that the strings has been initialized. sort (function (a, B) {return. localeCompare (B)}); // call the sort () method for sorting