不区分大小写的搜索


272

我正在尝试使用JavaScript中的两个字符串进行不区分大小写的搜索。

通常情况如下:

var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);

/i标志将不区分大小写。

但是我需要搜索第二个字符串。没有标志,它可以完美地工作:

var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);

如果将/i标记添加到上面的示例中,它将搜索searchstring而不是变量“ searchstring”中的内容(下一个示例不起作用):

var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);

我该如何实现?

Answers:


373

是的,使用.match而不是.search.match调用的结果将返回匹配自身的实际字符串,但仍可以将其用作布尔值。

var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';

if (result){
    alert('Matched');
}

在JavaScript中使用这样的正则表达式可能是最整齐,最明显的方法,但是请记住,它一个正则表达式,因此可以包含regex元字符。如果您想从其他地方获取字符串(例如,用户输入),或者想要避免不得不转义许多元字符,那么最好使用indexOf这样的方法:

matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.

if (string.toLowerCase().indexOf(matchString) != -1){
    alert('Matched');
}

9
抱歉,在第一个示例中如何将“最佳”转换为变量?string.match(/best/i);
Doug Molineux 2015年

5
为什么要使用.match布尔比较。搜索超出第一个结果。你需要它的第一场比赛之后停止.test.search做。在此处检查性能。
拉米

toLowerCase极有可能无法通过土耳其测试(moserware.com/2008/02/does-your-code-pass-turkey-test.html)和类似的案例转换问题。我不确定如何ReGex处理,但是如果我不得不猜测,我会说得更好。
奥哈德·施耐德

3
@DougMolineux可以使用RegExp对象构造函数。 var text = "best"; var exp = new RegExp(test, "i");。这与相同/best/i
Medeni Baykal,

174

更换

var result= string.search(/searchstring/i);

var result= string.search(new RegExp(searchstring, "i"));

7
这是一个相当混乱的方法,因为它采取措施来防止意外的正则表达式元字符。

35
丹,我怀疑我的答案应得-1。我试图通过更正他对JavaScript的不当使用来帮助ChrisBo,即:var result = string.search(/ searchstring / i); 到一个适当的位置,其中按他的意图使用了可变的搜索字符串。
谢尔盖·伊林斯基

8
丹(Dan)的权利(尽管他可能想说“ 没有措施”): s = 'a[b'; r = new RegExp(s)导致语法错误(
未定义

39

如果您只是在寻找一个字符串而不是一个更复杂的正则表达式,则可以使用indexOf()-但请记住要先将两个字符串都小写,因为indexOf()它区分大小写:

var string="Stackoverflow is the BEST"; 
var searchstring="best";

// lowercase both strings
var lcString=string.toLowerCase();
var lcSearchString=searchstring.toLowerCase();

var result = lcString.indexOf(lcSearchString)>=0;
alert(result);

或一行:

var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;

24

假设我们要在string变量needle中找到string变量haystack。有三个陷阱:

  1. 国际化的应用程序应避免string.toUpperCasestring.toLowerCase。请使用忽略大小写的正则表达式。例如,var needleRegExp = new RegExp(needle, "i");接着是needleRegExp.test(haystack)
  2. 通常,您可能不知道的值needle。注意needle不要包含任何正则表达式特殊字符。使用逃脱这些needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  3. 在其他情况下,如果要精确匹配needlehaystack,而忽略大小写,请确保"^""$"正则表达式构造函数的开头和结尾处添加。

考虑到第(1)和第(2)点,示例如下:

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);

4

ES6 +:

let string="Stackoverflow is the BEST";
let searchstring="best";


let found = string.toLowerCase()
                  .includes(searchstring.toLowerCase());

includes()返回true如果searchString在一个或多个位置或出现false其他。


2

如果您担心“未终止字符类”的情况,则删除所有非字母数字字符将很有帮助:

searchstring = searchstring.replace(/ [^ a-zA-Z 0-9] + / g,'');

2

我喜欢@ CHR15TO的答案,这与我在其他类似问题上看到的其他答案不同,该答案实际上显示了如何正确地转义用户提供的搜索字符串(而不是说有必要不显示方式)。

但是,它仍然很笨拙,并且可能相对较慢。那么,为什么不对编码人员的通用要求有一个特定的解决方案呢?(为什么不将其包括在ES6 API BTW中?)

我对类似问题的回答[ https://stackoverflow.com/a/38290557/887092]启用以下功能:

var haystack = 'A. BAIL. Of. Hay.';
var needle = 'bail.';
var index = haystack.naturalIndexOf(needle);

1

有两种不区分大小写的比较方式:

  1. 将字符串转换为大写,然后使用严格运算符(===)比较它们。严格的运算符对待操作数的方式在以下位置读取内容:http : //www.thesstech.com/javascript/relational-logical-operators

  2. 使用字符串方法进行模式匹配:

    使用“搜索”字符串方法进行不区分大小写的搜索。在以下网址了解有关搜索和其他字符串方法的信息:http : //www.thesstech.com/pattern-matching-using-string-methods

    <!doctype html>
      <html>
        <head>
          <script>
    
            // 1st way
    
            var a = "apple";
            var b = "APPLE";  
            if (a.toUpperCase() === b.toUpperCase()) {
              alert("equal");
            }
    
            //2nd way
    
            var a = " Null and void";
            document.write(a.search(/null/i)); 
    
          </script>
        </head>
    </html>

1

经常这样做,并使用一个接受varargs的简单5行原型。它速度快,可以在任何地方使用

myString.containsIgnoreCase('red','orange','yellow')

/**
 * @param {...string} var_strings Strings to search for
 * @return {boolean} true if ANY of the arguments is contained in the string
 */
String.prototype.containsIgnoreCase = function(var_strings) {
  const thisLowerCase = this.toLowerCase()
  for (let i = 0; i < arguments.length; i++) {
    let needle = arguments[i]
    if (thisLowerCase.indexOf(needle.toLowerCase()) >= 0) {
      return true
    }
  }
  return false
}

/**
 * @param {...string} var_strings Strings to search for
 * @return {boolean} true if ALL of the arguments are contained in the string
 */
String.prototype.containsAllIgnoreCase = function(var_strings) {
  const thisLowerCase = this.toLowerCase()
  for (let i = 0; i < arguments.length; i++) {
    let needle = arguments[i]
    if (thisLowerCase.indexOf(needle.toLowerCase()) === -1) {
      return false
    }
  }
  return true
}

// Unit test

let content = `
FIRST SECOND
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
FOO BAR
`

let data = [
  'foo',
  'Foo',
  'foobar',
  'barfoo',
  'first',
  'second'
]

let result
data.forEach(item => {
  console.log('Searching for', item)
  result = content.containsIgnoreCase(item)
  console.log(result ? 'Found' : 'Not Found')
})

console.log('Searching for', 'x, y, foo')
result = content.containsIgnoreCase('x', 'y', 'foo');
console.log(result ? 'Found' : 'Not Found')

console.log('Searching for all', 'foo, bar, foobar')
result = content.containsAllIgnoreCase('foo', 'bar', 'foobar');
console.log(result ? 'Found' : 'Not Found')

console.log('Searching for all', 'foo, bar')
result = content.containsAllIgnoreCase('foo', 'bar');
console.log(result ? 'Found' : 'Not Found')


0

您可以将所有内容变为小写:

var string="Stackoverflow is the BEST";
var searchstring="best";
var result= (string.toLowerCase()).search((searchstring.toLowerCase()));
alert(result);

-1

我注意到,如果用户输入文本字符串,但不选择任何自动完成选项而保留输入,即使字符串与数组中的一个一致,也不会在隐藏的输入中设置任何值。因此,借助其他答案,我做到了:

var $local_source = [{
        value: 1,
        label: "c++"
    }, {
        value: 2,
        label: "java"
    }, {
        value: 3,
        label: "php"
    }, {
        value: 4,
        label: "coldfusion"
    }, {
        value: 5,
        label: "javascript"
    }, {
        value: 6,
        label: "asp"
    }, {
        value: 7,
        label: "ruby"
    }];
    $('#search-fld').autocomplete({
        source: $local_source,
        select: function (event, ui) {
            $("#search-fld").val(ui.item.label); // display the selected text
            $("#search-fldID").val(ui.item.value); // save selected id to hidden input
            return false;
        },
        change: function( event, ui ) {

            var isInArray = false;

            $local_source.forEach(function(element, index){

                if ($("#search-fld").val().toUpperCase() == element.label.toUpperCase()) {
                    isInArray = true;
                    $("#search-fld").val(element.label); // display the selected text
                    $("#search-fldID").val(element.value); // save selected id to hidden input
                    console.log('inarray: '+isInArray+' label: '+element.label+' value: '+element.value);
                };

            });

            if(!isInArray){

                $("#search-fld").val(''); // display the selected text
                $( "#search-fldID" ).val( ui.item? ui.item.value : 0 );

            }
        } 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.