简体   繁体   中英

Get the index of the nth occurrence in a string

I'm trying to write a function that returns the index of a specific occurrence of a specific character from a string. However, I can only get it to successfully return the 1st or 2nd index. My function is as follows:

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

Entering these tests only works for the first 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

Does anyone have any ideas about how this could work for more than 2 instances? An example of how I'm using it would be to get the following:

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

Thanks for any help here.

In your code, you are not specifying nth occurance

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

Here you are trying to skip str.indexOf(char) + n-1 characters and continue the search Try this function

function getIndex(str,char,n) {
    return str.split('')
            .map((ch,index)=>ch===char?index:-1)
            .filter(in=>in!=-1)[n-1];
}
  • Say string is Hello and you are looking for 2nd l

  • Split the string into characters [H,e,l,l,0]

  • map them to index if it is the character you are looking for [-1,-1,2,3,-1]

  • Filter all -1 [2,3]

  • Take the 2nd index using n-1 that is 3

You can use split , slice & join to achieve your requirement.

Logic

First split your string with char then use slice to join split values upto nth occurrence. Then simply join with char . It's length will be your answer.

Check below.

 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 

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 ]
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
////

here is the fastest solution

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);

You could also use the regex exec method:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM