【问题标题】:Get the index of the nth occurrence in a string获取字符串中第 n 次出现的索引
【发布时间】:2018-12-07 12:44:38
【问题描述】:

我正在尝试编写一个函数,该函数返回字符串中特定字符的特定出现的索引。但是,我只能让它成功返回第一个或第二个索引。我的功能如下:

function getIndex(str,char,n) {
    return str.indexOf(char, str.indexOf(char) + n-1);
}

输入这些测试仅适用于前 2 个:

getIndex('https://www.example.example2.co.uk','.',2) // successfully returns 19
getIndex('https://www.example.example2.co.uk','.',1) // successfully returns 11
getIndex('https://www.example.example2.co.uk','.',3) // unsuccessfully returns 19

有没有人知道这如何适用于 2 个以上的实例?我如何使用它的一个例子是获得以下内容:

var str = 'https://www.example.example2.co.uk';
str.substring(31); // returns .uk
str.substring(28, 31); // returns .co

感谢您的帮助。

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用splitslicejoin 来满足您的要求。

逻辑

首先将splitchar 结合使用,然后使用slice 将拆分值连接到nth 出现。然后只需加入charlength 将是您的答案。

检查下面。

function getIndex(str, char, n) {
  return str.split(char).slice(0, n).join(char).length;
}

console.log(getIndex('https://www.example.example2.co.uk', '.', 2)) // returns 19
console.log(getIndex('https://www.example.example2.co.uk', '.', 1)) // returns 11
console.log(getIndex('https://www.example.example2.co.uk', '.', 3)) // returns 28

【讨论】:

    【解决方案2】:

    在您的代码中,您没有指定第 n 次出现

    str.indexOf(char, str.indexOf(char) + n-1);
    

    在这里您尝试跳过str.indexOf(char) + n-1 字符并继续搜索 试试这个功能

    function getIndex(str,char,n) {
        return str.split('')
                .map((ch,index)=>ch===char?index:-1)
                .filter(in=>in!=-1)[n-1];
    }
    
    • 说字符串是Hello,你正在寻找第二个l

    • 将字符串拆分为字符 [H,e,l,l,0]

    • 如果是您要查找的字符,则将它们映射到索引 [-1,-1,2,3,-1]

    • 过滤所有 -1 [2,3]

    • 使用 n-1 取第二个索引,即 3

    【讨论】:

      【解决方案3】:
      const search = '.';
      const indexOfAll = (arr, val) => arr.reduce((acc, curr, i) => (curr === val ? [...acc, i] : acc), []);
      
      indexOfAll(Array.from('https://www.example.example2.co.uk'), search);
      => [ 11, 19, 28, 31 ]
      

      【讨论】:

        【解决方案4】:
        function findIndex(str, searchCharacter, n){
            var length = str.length, i= -1;
            while(n-- && i++<length ){
                i= str.indexOf(searchCharacter, i);
                if (i < 0) break;
            }
            return i;
        }     
        
        var index = findIndex('https://www.example.example2.co.uk','.',3);
        console.log(index);
        ////
        //  28
        ////
        

        【讨论】:

          【解决方案5】:

          这是最快的解决方案

          function getIndex(str, character, n) {
              return str.split(character, n).join(character).length;
          }
          
          var v1 = getIndex("https://www.example.example2.co.uk", ".", 1);
          var v2 = getIndex("https://www.example.example2.co.uk", ".", 2);
          var v3 = getIndex("https://www.example.example2.co.uk", ".", 3);
          var v4 = getIndex("https://www.example.example2.co.uk", ".", 4);
          var v5 = getIndex("https://www.example.example2.co.uk", ".", 5);
          
          console.log(v1, v2, v3, v4, v5);
          

          【讨论】:

            【解决方案6】:

            您也可以使用正则表达式exec 方法:

            function getIndex(str, find, occ) {
              var regex = new RegExp(`\\${find}`, 'g');
              let arr, count = 0;
              while ((arr = regex.exec(str)) !== null) {
                if (++count == occ) return regex.lastIndex - 1; 
              }
            }
            
            const a = getIndex('https://www.example.example2.co.uk','.',2);
            const b = getIndex('https://www.example.example2.co.uk','.',1);
            const c = getIndex('https://www.example.example2.co.uk','.',3);
            
            console.log(a, b, c);

            【讨论】:

              猜你喜欢
              • 2010-09-16
              • 1970-01-01
              • 2016-11-21
              • 2013-01-06
              • 1970-01-01
              • 1970-01-01
              • 2014-08-08
              • 1970-01-01
              相关资源
              最近更新 更多