user8758206
user8758206

Reputation: 2191

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.

Upvotes: 0

Views: 1643

Answers (6)

Andy
Andy

Reputation: 63524

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

Upvotes: 1

Morhaf Shamia
Morhaf Shamia

Reputation: 382

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

Upvotes: 1

codemirror
codemirror

Reputation: 3572

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

Upvotes: 2

Unknown Joe
Unknown Joe

Reputation: 89

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 ]

Upvotes: 2

Karan
Karan

Reputation: 12619

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

Upvotes: 3

Deepak Kumar T P
Deepak Kumar T P

Reputation: 1076

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

Upvotes: 2

Related Questions