Javascript 如何获取字符串中的第n次出现?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14480345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the nth occurrence in a string?
提问by Adam
I would like to get the starting position of the 2ndoccurrence of ABCwith something like this:
我想用这样的东西来获得2nd发生的起始位置ABC:
var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16
How would you do it?
你会怎么做?
回答by Denys Séguret
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
)
回答by kennebec
You can also use the string indexOf without creating any arrays.
您还可以在不创建任何数组的情况下使用字符串 indexOf。
The second parameter is the index to start looking for the next match.
第二个参数是开始寻找下一个匹配项的索引。
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
*/
回答by ilovett
Working off of kennebec's answer, I created a prototype function which will return -1 if the nth occurence is not found rather than 0.
根据 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;
}
回答by Florian Margaine
Because recursion is always the answer.
因为递归总是答案。
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;
}
}
}
回答by Alnitak
Here's my solution, which just iterates over the string until nmatches have been found:
这是我的解决方案,它只是遍历字符串直到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
回答by Sharon Choe
This method creates a function that calls for the index of nth occurrences stored in an array
此方法创建一个函数,该函数调用存储在数组中的第 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
}
回答by Piotr
Shorter way and I think easier, without creating unnecessary strings.
更短的方法,我认为更容易,而不会创建不必要的字符串。
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
}
回答by Eric Amshukov
Using indexOfand Recursion:
使用indexOf和递归:
First check if the nth position passed is greater than the total number of substring occurrences. If passed, recursively go through each index until the nth one is found.
首先检查传递的第 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);
};
回答by sk8terboi87 ツ
Using [String.indexOf][1]
使用 [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
回答by Arul Benito
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));

