How do I compare two variables containing strings in JavaScript?

前端 未结 4 578
太阳男子
太阳男子 2020-12-30 01:34

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



        
相关标签:
4条回答
  • 2020-12-30 01:58

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

    0 讨论(0)
  • 2020-12-30 02:12

    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;
    }
    
    0 讨论(0)
  • 2020-12-30 02:20

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

    0 讨论(0)
  • 2020-12-30 02:22

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

    <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>
    
    0 讨论(0)
提交回复
热议问题