简体   繁体   English

如何比较两个字符串而不管它们的大小写?

[英]How to compare two strings regardless of their capitalization?

I have: 我有:

mytext = jQuery('#usp-title').val();

then I do 那我做

if(jQuery("#datafetch h2 a").text() == mytext) {

But one title could be: 但是一个标题可能是:

Space Mission just as well as space mission Space Missionspace mission

I cannot standardise the text format for other reasons therefore I am really looking at comparing two strings regardless of their capitalisation. 由于其他原因,我无法使文本格式标准化,因此我实际上是在比较两个字符串,无论它们的大小写如何。

UPDATE 更新

The thing is that I am using the input field as a search so the user could type space mission while the post title would be Space mission so the search result wouldn't be exact and i need the exact phrase instead. 事情是,我正在使用输入字段作为搜索,以便用户可以输入space mission而帖子标题将是Space mission因此搜索结果将不准确,而我需要准确的短语。

Complete code: 完整的代码:

<div id="datafetch"></div>

function fetch(){
  jQuery('#datafetch').empty();
  mytext = jQuery('#usp-title').val();
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', exactwords:  mytext },
        success: function(data) {
            jQuery('#datafetch').html( data );
        if(jQuery("#datafetch h2 a").text().toLowerCase().trim() == mytext.toLowerCase().trim()) {
            jQuery("#componi").attr("disabled", "disabled").hide();
        } else {
                jQuery("#componi").removeAttr("disabled", "disabled").show();
        }
            if(jQuery("#datafetch h2 a").text() != mytext) {
            jQuery("#fatto").hide();
            jQuery('#datafetch').empty();
        }
        }
    });

}

It's trickier actually because the search is coming from the text input, so it's about the query of the ajax i believe more than capitalisation, just a thought. 实际上,这比较棘手,因为搜索是来自文本输入的,所以它是关于查询ajax的问题​​,我认为这比大写字母更重要。 The latest code above gives no results by typing: 上面的最新代码无法通过键入以下内容产生任何结果:

space mission while the post title is Space mission space mission而职位是Space mission

UPDATE 2 更新2

Post article title: 发表文章标题:

Space Mission

User searches for 用户搜索

space mission

Console.log(data) gives correct result Console.log(数据)给出正确的结果

   <ul class="list-unstyled margin-top-80">
       <li>
            <h2><a target="_blank" href="example.com"">Space Mission</a></h2>
       </li>
   </ul>

Yet this doesn't happens: 但这不会发生:

jQuery('#datafetch').html( data );

if I insert the right words Space Mission does tho 如果我输入正确的词, Space Mission

Covert both toLowercase() 都隐藏到toLowercase()

"Space Mission".toLowerCase() == "space mission".toLowerCase()

In context of your question 根据您的问题

if(jQuery("#datafetch h2 a").text().toLowerCase() == mytext.toLowerCase()) {

Trimming in case user enters trailing or leading space, as suggested by @charlietfl 如果用户输入尾随空格或前导空格,则进行整理,如@charlietfl所建议

if(jQuery("#datafetch h2 a").text().trim().toLowerCase() == mytext.trim().toLowerCase()) {

Get the input result using jquery 使用jQuery获取输入结果

var string = jQuery("#datafetch h2 a").text()

and then you can try any of the following - 然后您可以尝试以下任一方法-

Simple string comparison : converting both to same case : 简单的字符串比较 :将两者都转换为相同的大小写:

string.toUpperCase() === "String".toUpperCase()

If you are fine with regex (notice the i option in regex) : 如果您对regex满意 (请注意regex中的i选项):

var otherString = /String/i
otherString.test(string)

There is "match" as well : 也有“匹配”:

string.match(/STRING/i)

match returns null value when no match found 如果找不到匹配项,则match返回null值

The accepted answer is correct and it does answer my original question, and that's why I accepted it. 接受的答案是正确的,并且确实回答了我的原始问题,这就是为什么我接受了它。 However, the issue was solved by using a setTimeout(function() as there was a little delay between the data populating the div and the check for the 2 value comparisons. 但是,通过使用setTimeout(function()解决了该问题,因为在填充div的数据和检查2个值的比较之间存在少许延迟。

function fetch(){
        jQuery.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'post',
            data: { action: 'data_fetch', exactwords:  jQuery('#usp-title').val() },
            success: function(data) {
                    jQuery("#datafetch").html(data);
                    setTimeout(function() {
                        var text1 = jQuery("#datafetch").find("h2").find("a").html();
                        var text1B = text1.toLowerCase();
                        var text2 = jQuery('#usp-title').val();
                        var text2B = text2.toLowerCase();
                        if(text1B == text2B) {
                            jQuery("#componi").attr("disabled", "disabled").hide();
                        } else {
                            jQuery("#componi").removeAttr("disabled", "disabled").show();
                            jQuery("#fatto").hide();
                            jQuery('#datafetch').empty();
                        }
                    }, 1000);
            }
        });
}

UPDATE 更新

Using .promise().done() was better 使用.promise().done()更好

function fetch(){
    var text1;
    var text1B;
    var text2;
    var text2B;
        jQuery.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'post',
            data: { action: 'data_fetch', exactwords:  jQuery('#usp-title').val() },
            success: function(data) {
                    jQuery("#datafetch").html(data).promise().done(function(){
                        text1 = jQuery("#datafetch").find("h2").find("a").html();
                        text1B = text1.toLowerCase();
                        text2 = jQuery('#usp-title').val();
                        text2B = text2.toLowerCase();
                        if (text1B != text2B) {
                            jQuery("#componi").removeAttr("disabled", "disabled").show();
                            jQuery("#fatto").hide();
                            jQuery('#datafetch').empty();
                        } else if (text1B == text2B) {
                            jQuery("#componi").attr("disabled", "disabled").hide();
                        }
                    });
            }
        });
}

UPDATE TWO 更新两次

This is what I finally used 这就是我最终使用的

function fetch(){
  jQuery.ajax({
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    type: 'post',
    data: { action: 'data_fetch', exactwords:  jQuery('#usp-title').val() },
    success: function(data) {
      var text2;
      var text2B;
      text2 = jQuery('#usp-title').val();
      text2B = text2.toLowerCase();
      jQuery("#datafetch").html(data).promise().done(function(){
        jQuery("#datafetch ul li h2 a").each(function() {
          var $this = jQuery(this);
          if ($this.text().toLowerCase() !== text2B) {
            $this.parent().parent().hide();
          } else if (text1B == text2B) {
            jQuery("#componi").attr("disabled", "disabled").hide();
          }
        });
      });
    }
  });
}

You can do like this 你可以这样

"Space Mission".replace(/\s+/g, "").toLowerCase() == "space    mission".replace(/\s+/g, "").toLowerCase()

The left hand side will be equal to spacemission same as the expression on the right sade 左侧将等于spacemission ,与右侧sade的表达式相同

It will first remove any white space even in between words & will convert to lower case. 它会首先删除单词之间的所有空白,甚至会转换为小写。 Removing white space is necessary because space mission is not same as space mission 必须删除空白空间,因为space missionspace mission

You will require to convert both strings to lowercase or uppercase and then do the comparison. 您将需要将两个字符串都转换为小写或大写,然后进行比较。

    var mytext = jQuery('#usp-title').val();
    if(jQuery("#datafetch h2 a").text().toLowerCase() == mytext.toLowerCase()) 
    {

    }

将两个字符串都转换为大写或小写

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM