我有以下几点:

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

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

有办法说拉尔必须不区分大小写吗?


当前回答

以下是我的看法:

脚本:

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

其他回答

为了做一个更好的搜索使用下面的代码,

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

在ES2016中,你还可以使用稍微更好/更简单/更优雅的方法(区分大小写):

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

或(不区分大小写):

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

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

这样更好~!

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

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

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

现在都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指的是下面的参数。所以用前缀代替。 不要使用“大小写不敏感”前缀会太长 “natural”是一个很好的候选词,因为默认区分大小写的比较首先对人类来说并不自然。

为什么不…:

toLowerCase() -可能重复调用同一个字符串上的toLowerCase。 RegExp—用变量搜索很麻烦。甚至RegExp对象也不得不转义字符