How to search for multiple sub-strings in a single query

indexof, javascript, regex

Solution

Here is one way of doing what I think you want.

var results = new Array();
for ( var i = 0; i < querywords.length; i++ ) {
    var regex = new RegExp( 
        '(?=.*\\b' + querywords[i].split(' ').join('\\b)(?=.*\\b') + '\\b)', 'i'
    );
    for ( var j = 0; j < links.length; j++ ) {
        if ( regex.test( links[j].text ) ) {
            results.push( links[j].element );
        }
    }
}

For example, if `querywords` contained the item `"red sweet strawberries"`, the `regex` created would be

/(?=.*\bred\b)(?=.*\bsweet\b)(?=.*\bstrawberries\b)/i

Three positive look-aheads are used so that strings which contain the three words on the same line pass the test (if they are surrounded by a word boundary).

Demo: JSFIDDLE.

Problem

I've come across a point from which I am unable to think further. Briefly, I have an `ul` with hundred of `li`, each `li` having tens of words as text; at the very top of the list I have put an input box for the user to type some keywords; let's say, for example, that I want to filter out from that huge list only the lines where the following three words exist in the same line: "red sweet strawberries". Being hit the search button, the lines are filtered out and there I have only two rows containing the words I am interested in. li1: "I hardly wait to eat some red sweet strawberries" li2: "It is summer and the red sweet strawberries are fresh now" Until this point everything is fine. The problem occurs when the three looked up words are separated by other words or characters along the string. So, taken the upper example, the filter would never show me the following line: li3: "The red and sweet strawberries are on the market now" So, here I lay down the entire function that filter and sort out the results from the upper example: ``` $(document).ready(function() { var links = new Array(); $("h4").each(function(index, element) { links.push({ text: $(this).text(), element: element }); }); $("#searchbutton").click(function() { var query = $("#inputtext").val(); var querywords = query.split(','); var results = new Array(); for(var i = 0; i < querywords.length; i++) { for(var j = 0; j < links.length; j++) { if (links[j].text.toLowerCase().indexOf(querywords[i].toLowerCase()) > -1) { results.push(links[j].element); } } } $("h4").each(function(index, element) { this.style.display = 'none'; }); for(var i = 0; i < results.length; i++) { results[i].style.display = 'block'; } }); }); ``` Is it possible to search for multiple sub-strings and get results, even if the sub-strings are separated by characters or other words ?

Original source