Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two variables containing strings in JavaScript?

Tags:

javascript

I want compare two variables, that are strings, but I am getting an error.

<script>
    var to_check=$(this).val();
    var cur_string=$("#0").text();
    var to_chk = "that";
    var cur_str= "that";

    if(to_chk==cur_str){
        alert("both are equal");
        $("#0").attr("class","correct");    
    } else {
        alert("both are not equal");
        $("#0").attr("class","incorrect");
    }
</script>

Is something wrong with my if statement?

like image 604
InvisibleWolf Avatar asked Apr 01 '13 05:04

InvisibleWolf


People also ask

Can we use == to compare strings in JavaScript?

In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.

Can we compare two strings in JavaScript?

Two strings in Javascript can be compared to check whether they are the same or not using different methods like toUpperCase(), localeCompare(), etc. We can also compare two strings in javascript using RegEx. Operators like greater than, or less than or equality operators to compare two strings.

How do you compare variables to strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

Can you use == when comparing strings?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .


1 Answers

=== is not necessary. You know both values are strings so you dont need to compare types.

function do_check()
{
  var str1 = $("#textbox1").val();
  var str2 = $("#textbox2").val();

  if (str1 == str2)
  {
    $(":text").removeClass("incorrect");
    alert("equal");
  }
  else
  {
    $(":text").addClass("incorrect");
    alert("not equal");
  }
}
.incorrect
{
  background: #ff8888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="textbox1" type="text">
<input id="textbox2" type="text">

<button onclick="do_check()">check</button>
like image 66
Anders Lindén Avatar answered Sep 19 '22 19:09

Anders Lindén