My version of a string search function


#1

Its basic but it works.
Given a string and a target set of characters the function loops for every character of the given target set checking for matches.
I did this because the original code from this exercise would return false positives, since it starts storing into the array when it finds a coincidence with the first character of "myName" variable

function search (string , target_set){
    var matches = 0;//declare counter variable
    for (var i = 0; i <= target_set.length; i++ ) {
        if (target_set.substring(i,i+string.length) == string.substring(0,string.length)){//Loop to check for matches
            var matches =+ 1;//counter that increases when a match is found
        }
    }
    console.log(matches);
}

#2

This is cool! However, you are missing the closing curly brace for the function. Also, you could further minify the match counter.

function search (string , target_set){
    var matches = 0;//declare counter variable
    for (var i = 0; i <= target_set.length; i++ ) {
        if (target_set.substring(i,i+string.length) == string.substring(0,string.length)){//Loop to check for matches
            matches += 1;//counter that increases when a match is found
        }
    }

    console.log(matches);
}

#3

You're right, thanks!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.