methuselah
methuselah

Reputation: 13216

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 search3 = "ever movie greatest the"

Using indexOf() only returns search1 false but search2,3 are true as well. How would I write a simple search algorithm to recognise instances where the words may not be in the right order or clumped together?

Upvotes: 3

Views: 175

Answers (1)

jfriend00
jfriend00

Reputation: 708016

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.

Upvotes: 4

Related Questions