Javascript 包含不区分大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8993773/
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-08-24 08:19:25  来源:igfitidea点击:

Contains case insensitive

javascriptstringcase-sensitivecase-insensitive

提问by Nate Pet

I have the following:

我有以下几点:

if (referrer.indexOf("Ral") == -1) { ... }

What I like to do is to make Ralcase insensitive, so that it can be RAl, rAl, etc. and still match.

我喜欢做的事情就是让Ral不区分大小写,因此,它可以是RAlrAl等,仍然匹配。

Is there a way to say that Ralhas to be case-insensitive?

有没有办法说Ral必须不区分大小写?

回答by Rob W

Add .toLowerCase()after referrer. This method turns the string in a lower case string. Then, use .indexOf()using ralinstead of Ral.

.toLowerCase()之后添加referrer。此方法将字符串转换为小写字符串。然后,使用.indexOf()usingral代替Ral

if (referrer.toLowerCase().indexOf("ral") === -1) { 

The same can also be achieved using a Regular Expression (especially useful when you want to test against dynamic patterns):

使用正则表达式也可以实现相同的目的(当您想针对动态模式进行测试时尤其有用):

if (!/Ral/i.test(referrer)) {
   //    ^i = Ignore case flag for RegExp

回答by Kfir Erez

Another options is to use the search method as follow:

另一种选择是使用搜索方法如下:

if (referrer.search(new RegExp("Ral", "i")) == -1) { ...

It looks more elegant then converting the whole string to lower case and it may be more efficient.
With toLowerCase()the code have two pass over the string, one pass is on the entire string to convert it to lower case and another is to look for the desired index.
With RegExpthe code have one pass over the string which it looks to match the desired index.

它看起来比将整个字符串转换为小写更优雅,并且可能更有效。
随着toLowerCase()代码有两个传过来的字符串,一个是通过对整个字符串将其转换为小写,另一个是寻找所需的索引。
使用RegExp代码对它看起来与所需索引匹配的字符串进行一次传递。

Therefore, on long strings I recommend to use the RegExpversion (I guess that on short strings this efficiency comes on the account of creating the RegExpobject though)

因此,在长字符串上,我建议使用该RegExp版本(我想在短字符串上,这种效率是由于创建RegExp对象的原因)

回答by gilly3

Use a RegExp:

使用正则表达式:

if (!/ral/i.test(referrer)) {
    ...
}

Or, use .toLowerCase():

或者,使用.toLowerCase()

if (referrer.toLowerCase().indexOf("ral") == -1)

回答by ?ukasz Matuszewski

From ES2016 you can also use slightly better / easier / more elegant method (case-sensitive):

从 ES2016 开始,您还可以使用更好/更简单/更优雅的方法(区分大小写):

if (referrer.includes("Ral")) { ... }

or (case-insensitive):

或(不区分大小写):

if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }

Here is some comparison of .indexOf()and .includes(): https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

下面是一些比较.indexOf().includes()https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

回答by cheeken

There are a couple of approaches here.

这里有几种方法。

If you want to perform a case-insensitive check for just this instance, do something like the following.

如果您只想对这个实例执行不区分大小写的检查,请执行以下操作。

if (referrer.toLowerCase().indexOf("Ral".toLowerCase()) == -1) {
    ...

Alternatively, if you're performing this check regularly, you can add a new indexOf()-like method to String, but make it case insensitive.

或者,如果您定期执行此检查,则可以向 中添加一个新indexOf()的类似方法String,但不区分大小写。

String.prototype.indexOfInsensitive = function (s, b) {
    return this.toLowerCase().indexOf(s.toLowerCase(), b);
}

// Then invoke it
if (referrer.indexOfInsensitive("Ral") == -1) { ...

回答by Kendall Frey

if (referrer.toUpperCase().indexOf("RAL") == -1) { ...

回答by Bakarali Sunasra

You can try this

你可以试试这个

str = "Wow its so COOL"
searchStr = "CoOl"

console.log(str.toLowerCase().includes(searchStr.toLowerCase()))

回答by alex_1948511

Example for any language:

任何语言的示例:

'My name is Хведор'.toLocaleLowerCase().includes('ХвЕдОр'.toLocaleLowerCase())

回答by Todd

It's 2016, and there's no clear way of how to do this? I was hoping for some copypasta. I'll have a go.

现在是 2016 年,没有明确的方法来做到这一点?我希望有一些copypasta。我去试试

Design notes: I wanted to minimize memory usage, and therefore improve speed - so there is no copying/mutating of strings. I assume V8 (and other engines) can optimise this function.

设计说明:我想最大限度地减少内存使用量,从而提高速度 - 所以没有字符串的复制/变异。我假设 V8(和其他引擎)可以优化这个功能。

//TODO: Performance testing
String.prototype.naturalIndexOf = function(needle) {
    //TODO: guard conditions here

    var haystack = this; //You can replace `haystack` for `this` below but I wan't to make the algorithm more readable for the answer
    var needleIndex = 0;
    var foundAt = 0;
    for (var haystackIndex = 0; haystackIndex < haystack.length; haystackIndex++) {
        var needleCode = needle.charCodeAt(needleIndex);
        if (needleCode >= 65 && needleCode <= 90) needleCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser
        var haystackCode = haystack.charCodeAt(haystackIndex);
        if (haystackCode >= 65 && haystackCode <= 90) haystackCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser

        //TODO: code to detect unicode characters and fallback to toLowerCase - when > 128?
        //if (needleCode > 128 || haystackCode > 128) return haystack.toLocaleLowerCase().indexOf(needle.toLocaleLowerCase();
        if (haystackCode !== needleCode)
        {
            foundAt = haystackIndex;
            needleIndex = 0; //Start again
        }
        else
            needleIndex++;

        if (needleIndex == needle.length)
            return foundAt;
    }

    return -1;
}

My reason for the name:

我取这个名字的原因:

  • Should have IndexOf in the name
  • Don't add a suffix - Of refers to the following parameter
  • Don't use "caseInsensitive" that's sooooo long
  • "natural" is a good candidate, because default case sensitive comparisons are not natural to humans in the first place.
  • 名称中应该有 IndexOf
  • 不加后缀-of指的是下面的参数
  • 不要使用太长的“caseInsensitive”
  • “自然”是一个很好的候选者,因为默认的区分大小写的比较首先对人类来说并不自然。

Why not...:

为什么不...:

  • toLowerCase()- potential repeated calls to toLowerCase on the same string.
  • RegExp- awkward to search with variable. Even the RegExp object is awkward having to escape characters
  • toLowerCase()- 可能在同一字符串上重复调用 toLowerCase。
  • RegExp- 用变量搜索很尴尬。即使是 RegExp 对象也很尴尬不得不转义字符

回答by A-Sharabiani

If referreris an array, you can use findIndex()

如果referrer是数组,则可以使用findIndex()

 if(referrer.findIndex(item => 'ral' === item.toLowerCase()) == -1) {...}