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?
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 (===)”.
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.
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.
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 .
===
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With