如何获取字符串中的第n次出现?


104

我想用这样的东西来获取2nd发生的开始位置ABC

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

你会怎么做?


第二次出现还是最后一次出现?:)
杰克

抱歉,我没有寻找最后一个索引。我正在寻找nth发生的开始位置,在这种情况下是第二个。
亚当

Answers:


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
如果您指定每个参数的含义,我会很好。
永远

1
@Foreever我只是实现了OP定义的功能
DenysSéguret2014年

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;
鲁芬2015年

70

您也可以使用字符串indexOf而不创建任何数组。

第二个参数是开始寻找下一个匹配项的索引。

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 '16

1
我更喜欢这个答案,而不是接受的答案,因为当我测试一个不存在的第二个实例时,另一个答案返回了第一个字符串的长度,而这个字符串返回了-1。赞成票,谢谢。
约翰(John)

2
这不是JS的内置功能,这很荒谬。
Sinister Beard

20

根据肯尼贝克的答案,我创建了一个原型函数,如果未找到第n个事件,则将返回-1而不是0。

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不能防止单引号被黑。许多专业的编码不仅具有良好的习惯,而且还理解为什么这种习惯很重要。:-)
约翰(John)

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>

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.