JavaScript to determine whether two strings are equal

  • 2020-07-21 06:51:32
  • OfStack

The user's input values are all converted to uppercase (or lowercase), and then compared again:

You may first refer to an example:

How does js determine an instance where two strings are equal

https://www.ofstack.com/article/154827.htm


  var name = document.form1.txtUserName.value.toLowerCase();


  if(name == "urname")


  {


   // statements go here.


  }



JavaScript has two equality operators. The standard "==" is completely backward compatible. If two operand types are not 1, it will automatically cast the operand at some point. Consider the following assignment statement:


  var strA = "i love you!";


  var strB = new String("i love you!");



The two variables have the same sequence of characters but different data types, string and object, and when using the "==" operator, JavaScript tries various evaluations to detect whether the two are equal in some cases. So the following expression results in true: strA == strB.


The second operator, which is "strict" and "===", is not so lenient in evaluation and does not cast. So the value of the expression strA === strB is false, although both variables hold the same value.


Sometimes the logic of the code requires you to determine if two values are not equal, and there are two options: "! =" and strict "! ==", the relationship is similar to "==" and "===".


Discussion:


"= =" and "! =" When evaluating, look for value matches as much as possible, but you might want to do an explicit cast before comparing to "help" them do their job. For example, if you want to determine whether a user's input value (string) is equal to a number, you can ask "==" to do the conversion for you:


  if(document.form1.txtAge.value == someNumericVar) { ... }



You can also switch ahead of time:


  if(parseInt(document.form1.txtAge.value) == someNumericVar) { ... }



If you are used to a strongly typed programming language (C#,Java, etc.), you can continue this habit here, which will also make the program more readable.

One case to note is the locale of the computer. If you use" < "And" > "To compare strings, then JavaScript would compare them as Unicode, but apparently people don't read text as Unicode when browsing the web :) in Spanish, for example, "ch" would be one character between "c" and "d" in the traditional order. localeCompare() provides a way to help you use character collation under the default locale.


 var strings; //  The array of strings to sort, assuming it is initialized 


 strings.sort(function(a,b) { return a.localeCompare(b) }); //  call sort() Method to sort 


Related articles: