Multiple Partial Matches in Regex

What is the proper regular expression for finding multiple partial matches in a string?

For context, I have a Javascript application which allows users to search for colleges by name. I first get the user's input then use the .includes() function to see if the input string matches a college name. This works, however, you have to type in the name of the college in sequence. For example entering georgia inst will return Georgia Institute of Technology. However, entering georgia tech does not result in a match.

I believe I should use expression.test(String) but I do not know what the proper regex should be. Any help would be greatly appreciated.

Another example is if a user wants to search for California Institute of Technology they should be able to get a match by typing in cal tech.

2 answers

  • answered 2017-06-17 18:45 Karen Grigoryan

    Try this:

    const string = "Georgia Institute of Technology";
    const fuzzyMatch = 
    (patternString, stringToMatch) => {
      // creating a string to pass into RegExp constructor
      // by replacing all occurencies of spaces "  " between words with
      // all matching regex selector ".*"
      // so for example if patternString is "geo inst tech"
      // after replacement it becomes "geo.*inst.*tech"
      const regExpString = patternString.replace(/\s/g, '.*');
      // here we create a literal regular expression aka
      // /geo.*inst.*tech/ig
      // and testing it against the stringToMatch
      return new RegExp(regExpString, 'ig')
    console.log(fuzzyMatch("geo inst", "Georgia Institute of Technology"));
    console.log(fuzzyMatch("Geo Tech", "Georgia Institute of Technology"));

  • answered 2017-06-17 18:45 Gaurav Tamhan

    Thank you for all your responses! Based on them I was able to do exactly what I was looking for. I split up the search terms and then used regex to determine if there were any matches.

    const str = "Georgia Institute of Technology";
    // Obtains the input value, separates terms by spaces, 
    // and places them in an array
    // For example: if input was 'geo tech'
    // then searchTerms = ['geo', 'tech']
    var input = document.getElementById("searchField").value;
    var searchTerms = input.split(" ");
    // Joins the search terms into a valid regex expression: /geo.*tech/i
    var value = new RegExp(searchTerms.join('.*'), "i").test(str);
    // In this case value = true!