web-dev-qa-db-ja.com

大文字と小文字を区別しない

私は以下を持っています:

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

Ralname__を大文字と小文字を区別しないようにすることで、RAlname__、rAlname__などにしても一致させることができます。

Ralname__では、大文字と小文字が区別されないと言う方法はありますか?

348
Nate Pet

referrerの後に.toLowerCase()を追加します。このメソッドは、文字列を小文字に変換します。次に、ralの代わりにRalを使用して.indexOf()を使用します。

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

同じことが正規表現を使っても達成できます(動的パターンに対してテストしたいときに特に役立ちます):

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

別の方法は、検索方法を以下のように使用することです。

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

文字列全体を小文字に変換するよりもエレガントに見え、より効率的な場合があります。
toLowerCase()では、コードは文字列を2回通過します。1回は文字列全体を小文字に変換し、もう1回は目的のインデックスを探すことです。
RegExpを使用すると、コードは文字列を1回通過して、目的のインデックスに一致するように見えます。

したがって、長い文字列の場合はRegExpバージョンを使用することをお勧めします(短い文字列の場合、この効率はRegExpオブジェクトを作成するために生じると思います)。

84
Kfir Erez

正規表現を使う:

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

あるいは、.toLowerCase()を使用してください。

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

ここにいくつかのアプローチがあります。

このインスタンスだけで大文字と小文字を区別しないチェックを実行したい場合は、次のようにしてください。

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) { ...
10
cheeken

ES2016からは、もう少し優れた/簡単な/よりエレガントな方法を使用することもできます。

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

または

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

これが.indexOf().includes()の比較です: https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

9
if (referrer.toUpperCase().indexOf("RAL") == -1) { ...
4
Kendall Frey

それは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を含める必要があります
  • 接尾辞を追加しない - Ofは次のパラメータを参照します
  • あまりにも長い "caseInsensitive"を使用しないでください
  • デフォルトの大文字と小文字を区別する比較は、そもそも人間にとって自然なことではないので、「自然」が良い候補です。

何故なの...:

  • toLowerCase() - 同じ文字列に対してtoLowerCaseを繰り返し呼び出す可能性がある.
  • RegExp - 変数で検索するのが面倒です。 RegExpオブジェクトでさえ文字をエスケープするのは面倒です
1
Todd

referrerが配列の場合、findIndex()を使用できます。

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

より良い検索をするには、次のコードを使います。

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()は一致を見つけられませんでした。 indexOf()を使用して大/小文字を区別しない検索を実行するには、両方のストリングを大文字または小文字にすることができます。つまり、2番目のalert()のように、JavaScriptは探している文字列の出現をチェックするだけで、大文字と小文字は区別されません。

参照、 http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm

1
Diganta Kumar

これが私の考えです:

スクリプト

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

0

任意の言語の例:

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