包含不区分大小写

发布于 2024-12-28 15:57:52 字数 240 浏览 1 评论 0原文

我有以下内容:

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

我喜欢做的是使 Ral 不区分大小写,以便它可以是 RAlrAl 等,并且仍然匹配。

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

I have the following:

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

说好的呢 2025-01-04 15:57:52

referrer 之后添加 .toUpperCase()。该方法将字符串转换为大写字符串。然后,使用 .indexOf() 使用 RAL 而不是 Ral

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

使用正则表达式也可以实现相同的目的(当您想要测试动态模式时特别有用):

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

Add .toUpperCase() after referrer. This method turns the string into an upper case string. Then, use .indexOf() using RAL instead of Ral.

if (referrer.toUpperCase().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
梦幻的味道 2025-01-04 15:57:52

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

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

它看起来更优雅,然后将整个字符串转换为小写,并且可能更有效。
使用 toLowerCase() 代码对字符串进行两次传递,一次是在整个字符串上将其转换为小写,另一次是查找所需的索引。
使用 RegExp ,代码只需遍历一次看起来与所需索引匹配的字符串。

因此,对于长字符串,我建议使用 RegExp 版本(我猜测在短字符串上这种效率来自于创建 RegExp 对象)

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 RegExp the code have one pass over the string which it looks to match the desired index.

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

梦归所梦 2025-01-04 15:57:52

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

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

或(不区分大小写):

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

以下是 .indexOf().includes( )
https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

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

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

美男兮 2025-01-04 15:57:52

使用正则表达式:

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

或者使用 .toLowerCase()

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

Use a RegExp:

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

Or, use .toLowerCase():

if (referrer.toLowerCase().indexOf("ral") == -1)
可是我不能没有你 2025-01-04 15:57:52

这里有几种方法。

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

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

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

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

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

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.

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

// Then invoke it
if (referrer.indexOfInsensitive("Ral") == -1) { ...
筑梦 2025-01-04 15:57:52

你可以试试这个

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

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

You can try this

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

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

伴我老 2025-01-04 15:57:52

以下是按照 ES6 按性能降序排列的选项

包含

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

IndexOf (这有时会提供与包含相似或更好的结果)

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

匹配

if (referrer.match(new RegExp("Ral", 'i'))) { ... }

基准结果: https://jsben.ch/IBbnl

Here are the options as per ES6 in decreasing order of performance

Includes

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

IndexOf (this sometimes gives similar or better results than Includes)

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

Match

if (referrer.match(new RegExp("Ral", 'i'))) { ... }

Benchmark results: https://jsben.ch/IBbnl

甜点 2025-01-04 15:57:52

任何语言的示例:

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

Example for any language:

'My name is Хведор'.toLocaleLowerCase().includes('ХвЕдОр'.toLocaleLowerCase())
不念旧人 2025-01-04 15:57:52
if (referrer.toUpperCase().indexOf("RAL") == -1) { ...
if (referrer.toUpperCase().indexOf("RAL") == -1) { ...
好菇凉咱不稀罕他 2025-01-04 15:57:52

现在已经是 2016 年了,还没有明确的方法来做到这一点吗?我希望能吃到一些复制意大利面。我会去尝试一下。

设计说明:我想最大限度地减少内存使用,从而提高速度 - 所以没有字符串的复制/变异。我认为 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;
}

我的名字理由:

  • 名称中应该有 IndexOf
  • 不要添加后缀词 - IndexOf 指的是以下参数。因此,请添加前缀。
  • 不要使用“caseInsensitive”前缀太长,
  • “natural”是一个很好的候选者,因为默认的区分大小写的比较首先对人类来说并不自然。

为什么不...:

  • toLowerCase() - 可能会在同一字符串上重复调用 toLowerCase。
  • RegExp - 使用变量搜索很尴尬。即使是 RegExp 对象也很尴尬,必须转义字符

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.

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.

//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 word - IndexOf refers to the following parameter. So prefix something instead.
  • Don't use "caseInsensitive" prefix would be sooooo long
  • "natural" is a good candidate, because default case sensitive comparisons are not natural to humans in the first place.

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
层林尽染 2025-01-04 15:57:52

为了进行更好的搜索,请使用以下代码,

var myFav   = "javascript";
var theList = "VB.NET, C#, PHP, Python, JavaScript, and Ruby";

// Check for matches with the plain vanilla indexOf() method:
alert( theList.indexOf( myFav ) );

// Now check for matches in lower-cased strings:
alert( theList.toLowerCase().indexOf( myFav.toLowerCase() ) );

在第一个alert()中,JavaScript返回“-1” - 换句话说,indexOf()没有找到匹配项:这只是因为“JavaScript”在第一个中是小写的字符串,并在第二个中正确大写。要使用indexOf()执行不区分大小写的搜索,您可以将两个字符串设置为大写或小写。这意味着,就像在第二个alert()中一样,JavaScript只会检查您要查找的字符串是否出现,而忽略大小写。

参考,
http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm

To do a better search use the following code,

var myFav   = "javascript";
var theList = "VB.NET, C#, PHP, Python, JavaScript, and Ruby";

// Check for matches with the plain vanilla indexOf() method:
alert( theList.indexOf( myFav ) );

// Now check for matches in lower-cased strings:
alert( theList.toLowerCase().indexOf( myFav.toLowerCase() ) );

In the first alert(), JavaScript returned "-1" - in other words, indexOf() did not find a match: this is simply because "JavaScript" is in lowercase in the first string, and properly capitalized in the second. To perform case-insensitive searches with indexOf(), you can make both strings either uppercase or lowercase. This means that, as in the second alert(), JavaScript will only check for the occurrence of the string you are looking for, capitalization ignored.

Reference,
http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm

尘世孤行 2025-01-04 15:57:52

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

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

If referrer is an array, you can use findIndex()

 if(referrer.findIndex(item => 'ral' === item.toLowerCase()) == -1) {...}
你没皮卡萌 2025-01-04 15:57:52

这是我的看法:

脚本

var originalText = $("#textContainer").html()
$("#search").on('keyup', function () {
  $("#textContainer").html(originalText)
  var text = $("#textContainer").html()
  var val = $("#search").val()
  if(val=="") return;
  var matches = text.split(val)
  for(var i=0;i<matches.length-1;i++) {
    var ind =  matches[i].indexOf(val)
    var len = val.length
      matches[i] = matches[i] + "<span class='selected'>" + val + "</span>"
  }
  $("#textContainer").html(matches.join(""))

HTML:

<input type="text" id="search">
<div id="textContainer">
lorem ipsum is simply dummy text of the printing and typesetting industry. lorem ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of letraset sheets containing lorem ipsum passages, and more recently with desktop publishing software like Aldus pagemaker including versions of lorem ipsum.</div>

代码笔

Here's my take:

Script:

var originalText = $("#textContainer").html()
$("#search").on('keyup', function () {
  $("#textContainer").html(originalText)
  var text = $("#textContainer").html()
  var val = $("#search").val()
  if(val=="") return;
  var matches = text.split(val)
  for(var i=0;i<matches.length-1;i++) {
    var ind =  matches[i].indexOf(val)
    var len = val.length
      matches[i] = matches[i] + "<span class='selected'>" + val + "</span>"
  }
  $("#textContainer").html(matches.join(""))

HTML:

<input type="text" id="search">
<div id="textContainer">
lorem ipsum is simply dummy text of the printing and typesetting industry. lorem ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of letraset sheets containing lorem ipsum passages, and more recently with desktop publishing software like Aldus pagemaker including versions of lorem ipsum.</div>

Codepen

魂牵梦绕锁你心扉 2025-01-04 15:57:52

这样就更好了~!

if (~referrer.toUpperCase().indexOf("RAL")) { 
    console.log("includes")
}

输入图片此处描述

It is better~!

if (~referrer.toUpperCase().indexOf("RAL")) { 
    console.log("includes")
}

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文