HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Returning index of nth occurrence of a substring

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nthsubstringreturningoccurrenceindex

Problem

I've built a JavaScript function returning the index of the nth occurrence of a substring in a string.

$(document).ready(function() {

        var containingString = '.this.that.';
        subString = '.';

        var index = GetIndexOfSubstring(containingString, subString, 2);

    });

    function GetIndexOfSubstring(containingString, subString, occurrenceNumberOfSubString) 
    {
        tokens = containingString.split(subString);
        var numberOfSubStrings = tokens.length - 1;

        if (occurrenceNumberOfSubString > numberOfSubStrings)
            return "Error";

        var index = 0 + occurrenceNumberOfSubString - 1;

        for(var c = 0; c < occurrenceNumberOfSubString; c++)
        {
            var i = containingString.indexOf(subString);
            var sub = containingString.substr(i + 1);
            containingString = sub;
            index += i;
        }

        return index;
    }


As far as I can see, the function works correctly. Is there is an easier way to accomplish the goal? Also, can the function be improved?

Solution

There's no need to split the original string or slice away at the string, you can just use the built in indexOf, keeping track of how many times you've looked for the substring. As a personal preference, I'd also use smaller, not as bombastic, variables names.

Also, there's absolutely no need to include jQuery in this - the $(document).ready is redundant.

function GetSubstringIndex(str, substring, n) {
    var times = 0, index = null;

    while (times < n && index !== -1) {
        index = str.indexOf(substring, index+1);
        times++;
    }

    return index;
}

Code Snippets

function GetSubstringIndex(str, substring, n) {
    var times = 0, index = null;

    while (times < n && index !== -1) {
        index = str.indexOf(substring, index+1);
        times++;
    }

    return index;
}

Context

StackExchange Code Review Q#10295, answer score: 13

Revisions (0)

No revisions yet.