我想得到这样的事情2nd发生的起始位置ABC:
var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16
你会怎么做?
我想得到这样的事情2nd发生的起始位置ABC:
var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16
你会怎么做?
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
)
您还可以在不创建任何数组的情况下使用字符串 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
*/
根据 kennebec 的回答,我创建了一个原型函数,如果没有找到第 n 次出现而不是 0,它将返回 -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;
}
因为递归总是答案。
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;
        }
    }
}
这是我的解决方案,它只是遍历字符串直到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