如何比较 JavaScript 中包含字符串的两个变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15737974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:54:26  来源:igfitidea点击:

How do I compare two variables containing strings in JavaScript?

javascript

提问by InvincibleWolf

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?

我的 if 语句有问题吗?

采纳答案by Anders Lindén

===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>

回答by anztrax

instead of using the ==sign, more safer use the ===sign when compare, the code that you post is work well

而不是使用==标志,比较时使用标志更安全===,您发布的代码运行良好

回答by Sivakumar Jallu

I used below function to compare two strings and It is working good.

我使用下面的函数来比较两个字符串,它运行良好。

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

回答by Kiran Chenna

You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1if the string not equals, 0for strings equal and 1if string1 is sorted after string2.

您可以使用 javascript 专用字符串比较方法string1.localeCompare(string2)。这将分为五个你-1如果字符串不等于,0字符串相等,1如果string1为字符串2后排序。

<script>
    var to_check=$(this).val();
    var cur_string=$("#0").text();
    var to_chk = "that";
    var cur_str= "that";
    if(to_chk.localeCompare(cur_str) == 0){
        alert("both are equal");
        $("#0").attr("class","correct");    
    } else {
        alert("both are not equal");
        $("#0").attr("class","incorrect");
    }
</script>