文字列のn番目の出現を取得するにはどうすればよいですか?


104

私は次のようなもので2nd発生の開始位置を取得ABCしたいと思います:

var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16

どうしますか


2回目ですか、最後ですか?:)
ジャック・

混乱してすみません、最後のインデックスは探していません。nth発生の開始位置、この場合は2番目を探しています。
アダム

回答:


158

const string = "XYZ 123 ABC 456 ABC 789 ABC";

function getPosition(string, subString, index) {
  return string.split(subString, index).join(subString).length;
}

console.log(
  getPosition(string, 'ABC', 2) // --> 16
)


26
私は実際にはこの答えが好きではありません。無制限の長さの入力が与えられると、不必要に長さのない配列が作成され、そのほとんどが破棄されます。次のfromIndex引数を繰り返し使用するだけで、より高速で効率的になりますString.indexOf
Alnitak

3
function getPosition(str, m, i) { return str.split(m, i).join(m).length; }
コピー

9
各パラメータの意味を指定していただければ良かったと思います。
Foreever

1
@Foreever OPで定義された関数を単純に実装した
DenysSéguret'10年

5
これは、<のi出現がある場合、文字列の長さを提供しますm。つまり、getPosition("aaaa","a",5)を与えるの4と同じようにgetPosition("aaaa","a",72)!そのような場合は-1が必要だと思います。var ret = str.split(m, i).join(m).length; return ret >= str.length ? -1 : ret;また、キャッチi <= 0したいかもしれませんreturn ret >= str.length || i <= 0 ? -1 : ret;
ruffin

70

配列を作成せずに文字列indexOfを使用することもできます。

2番目のパラメーターは、次の一致の検索を開始するインデックスです。

function nthIndex(str, pat, n){
    var L= str.length, i= -1;
    while(n-- && i++<L){
        i= str.indexOf(pat, i);
        if (i < 0) break;
    }
    return i;
}

var s= "XYZ 123 ABC 456 ABC 789 ABC";

nthIndex(s,'ABC',3)

/*  returned value: (Number)
24
*/

長さのキャッシュがあり、Stringプロトタイプを拡張しないため、このバージョンが好きです。
Christophe Roussy 2015

8
jsperfによると、この方法は受け入れられた回答よりもはるかに高速です
boop

インクリメントi:以下混乱行うことができますvar i; for (i = 0; n > 0 && i !== -1; n -= 1) { i = str.indexOf(pat, /* fromIndex */ i ? (i + 1) : i); } return i;
hlfcoding

1
存在しない2番目のインスタンスをテストしたとき、他の回答が最初の文字列の長さを返し、これが-1を返したので、私はこれを受け入れられた回答よりも好みます。賛成票をいただき、ありがとうございます。
ジョン

2
これがJSの組み込み機能ではないことはばかげています。
Sinister Beard

20

kennebecの答えに基づいて、0ではなくn番目の出現が見つからない場合に-1を返すプロトタイプ関数を作成しました。

String.prototype.nthIndexOf = function(pattern, n) {
    var i = -1;

    while (n-- && i++ < this.length) {
        i = this.indexOf(pattern, i);
        if (i < 0) break;
    }

    return i;
}

2
決して 今までに意図せずに、このプロトタイプで上書きなる可能性がネイティブ機能の最終的な適応として、キャメルケースを使用していません。この場合、すべての小文字とアンダースコア(URLのダッシュ)をお勧めしますString.prototype.nth_index_of。あなたの名前がユニークでクレイジーだと思っていても、世界はそれがもっとクレイジーにできることを証明します。
ジョン

特にプロトタイピングを行う場合はそうです。確かに、だれもその特定のメソッド名を使用することはできませんが、自分でそうすることを許可することによって、悪い習慣を作ります。重要な例けれども異なる:常に SQLを実行するときにデータを囲むINSERTようmysqli_real_escape_stringではない単一引用符ハックから保護します。プロのコーディングの多くは、良い習慣を持っているだけでなく、なぜそのような習慣が重要であるかを理解しています。:-)
ジョン

1
文字列プロトタイプを拡張しないでください。

4

なぜなら、再帰が常に答えだからです。

function getPosition(input, search, nth, curr, cnt) {
    curr = curr || 0;
    cnt = cnt || 0;
    var index = input.indexOf(search);
    if (curr === nth) {
        if (~index) {
            return cnt;
        }
        else {
            return -1;
        }
    }
    else {
        if (~index) {
            return getPosition(input.slice(index + search.length),
              search,
              nth,
              ++curr,
              cnt + index + search.length);
        }
        else {
            return -1;
        }
    }
}

1
@RenanCoelhoチルダ(~:)JavaScriptでビットごとのNOT演算子あるdeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
セバスチャン・

2

これが私の解決策です。n一致が見つかるまで文字列を反復処理します。

String.prototype.nthIndexOf = function(searchElement, n, fromElement) {
    n = n || 0;
    fromElement = fromElement || 0;
    while (n > 0) {
        fromElement = this.indexOf(searchElement, fromElement);
        if (fromElement < 0) {
            return -1;
        }
        --n;
        ++fromElement;
    }
    return fromElement - 1;
};

var string = "XYZ 123 ABC 456 ABC 789 ABC";
console.log(string.nthIndexOf('ABC', 2));

>> 16

2

このメソッドは、配列に格納されているn番目のオカレンスのインデックスを呼び出す関数を作成します

function nthIndexOf(search, n) { 
    var myArray = []; 
    for(var i = 0; i < myString.length; i++) { //loop thru string to check for occurrences
        if(myStr.slice(i, i + search.length) === search) { //if match found...
            myArray.push(i); //store index of each occurrence           
        }
    } 
    return myArray[n - 1]; //first occurrence stored in index 0 
}

上記のコードでmyStringを定義したとは思わないので、myStr === myStringかどうかはわかりませんか?
セスエデン

1

短い方が簡単で、不要な文字列を作成する必要はありません。

const findNthOccurence = (string, nth, char) => {
  let index = 0
  for (let i = 0; i < nth; i += 1) {
    if (index !== -1) index = string.indexOf(char, index + 1)
  }
  return index
}

0

使用indexOf再帰

最初に、渡されたn番目の位置が部分文字列の出現回数の合計より大きいかどうかを確認します。渡された場合、n番目のインデックスが見つかるまで、各インデックスを再帰的に調べます。

var getNthPosition = function(str, sub, n) {
    if (n > str.split(sub).length - 1) return -1;
    var recursePosition = function(n) {
        if (n === 0) return str.indexOf(sub);
        return str.indexOf(sub, recursePosition(n - 1) + 1);
    };
    return recursePosition(n);
};

0

使用する [String.indexOf][1]

var stringToMatch = "XYZ 123 ABC 456 ABC 789 ABC";

function yetAnotherGetNthOccurance(string, seek, occurance) {
    var index = 0, i = 1;

    while (index !== -1) {
        index = string.indexOf(seek, index + 1);
        if (occurance === i) {
           break;
        }
        i++;
    }
    if (index !== -1) {
        console.log('Occurance found in ' + index + ' position');
    }
    else if (index === -1 && i !== occurance) {
        console.log('Occurance not found in ' + occurance + ' position');
    }
    else {
        console.log('Occurance not found');
    }
}

yetAnotherGetNthOccurance(stringToMatch, 'ABC', 2);

// Output: Occurance found in 16 position

yetAnotherGetNthOccurance(stringToMatch, 'ABC', 20);

// Output: Occurance not found in 20 position

yetAnotherGetNthOccurance(stringToMatch, 'ZAB', 1)

// Output: Occurance not found

0
function getStringReminder(str, substr, occ) {
   let index = str.indexOf(substr);
   let preindex = '';
   let i = 1;
   while (index !== -1) {
      preIndex = index;
      if (occ == i) {
        break;
      }
      index = str.indexOf(substr, index + 1)
      i++;
   }
   return preIndex;
}
console.log(getStringReminder('bcdefgbcdbcd', 'bcd', 3));

-2

StackOverflowに関する別の質問のために次のコードをいじってみましたが、ここではそれが適切だと思いました。関数printList2は正規表現の使用を許可し、すべての出現を順番にリストします。(printListは以前の解決策の試みでしたが、多くの場合失敗しました。)

<html>
<head>
<title>Checking regex</title>
<script>
var string1 = "123xxx5yyy1234ABCxxxabc";
var search1 = /\d+/;
var search2 = /\d/;
var search3 = /abc/;
function printList(search) {
   document.writeln("<p>Searching using regex: " + search + " (printList)</p>");
   var list = string1.match(search);
   if (list == null) {
      document.writeln("<p>No matches</p>");
      return;
   }
   // document.writeln("<p>" + list.toString() + "</p>");
   // document.writeln("<p>" + typeof(list1) + "</p>");
   // document.writeln("<p>" + Array.isArray(list1) + "</p>");
   // document.writeln("<p>" + list1 + "</p>");
   var count = list.length;
   document.writeln("<ul>");
   for (i = 0; i < count; i++) {
      document.writeln("<li>" +  "  " + list[i] + "   length=" + list[i].length + 
          " first position=" + string1.indexOf(list[i]) + "</li>");
   }
   document.writeln("</ul>");
}
function printList2(search) {
   document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");
   var index = 0;
   var partial = string1;
   document.writeln("<ol>");
   for (j = 0; j < 100; j++) {
       var found = partial.match(search);
       if (found == null) {
          // document.writeln("<p>not found</p>");
          break;
       }
       var size = found[0].length;
       var loc = partial.search(search);
       var actloc = loc + index;
       document.writeln("<li>" + found[0] + "  length=" + size + "  first position=" + actloc);
       // document.writeln("  " + partial + "  " + loc);
       partial = partial.substring(loc + size);
       index = index + loc + size;
       document.writeln("</li>");
   }
   document.writeln("</ol>");

}
</script>
</head>
<body>
<p>Original string is <script>document.writeln(string1);</script></p>
<script>
   printList(/\d+/g);
   printList2(/\d+/);
   printList(/\d/g);
   printList2(/\d/);
   printList(/abc/g);
   printList2(/abc/);
   printList(/ABC/gi);
   printList2(/ABC/i);
</script>
</body>
</html>

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.