Skip to content Skip to sidebar Skip to footer

Refining The JavaScript IndexOf Statement

I'm writing a simple search algorithm in JavaScript. var title = 'The Greatest Movie Ever Made is here!'; var search1 = 'the greATEST movie'; var search2 = 'here IS made' var searc

Solution 1:

Here's a function that would tell you if all the words in the search string existed in the target without regard for case or word boundaries.

function findMatch(data, target) {
    var words = data.toUpperCase().split(/\s/);
    if (words.length === 0) {return(false);}
    var uTarget = target.toUpperCase().replace(/\s/, "");
    var matchCnt = 0;
    for (var i = 0; i < words.length; i++) {
        if (uTarget.indexOf(words[i]) != -1) {
            ++matchCnt;
        }
    }
    return(matchCnt === words.length);
}

This algorithm does not force word boundaries so searching for "an" will match if the target contains "and" or "answer". Enforcing word boundaries would take a little more code that understood what a valid word boundary was.


Post a Comment for "Refining The JavaScript IndexOf Statement"