-1

I have a search bar which would search for places, I only want to return results if the value of the input matches at least two words regardless of their positioning. I've tried using startsWith but this would only match those starting with.

If I want to search for Central Park, I could either type in the search bar "New york central park" or "Central Park New York" or simply "Central Park" and it will return the result but if I only type in "Park" or "Central", Central Park should not be returned yet

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ian Santos
  • 127
  • 1
  • 2
  • 11
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match is a better match for your needs, and don't forget to include an space in your regex – malarres Aug 13 '20 at 06:36
  • Does this answer your question? [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – jonrsharpe Aug 13 '20 at 06:36
  • Regex isn’t going to take care of the word-comparison part, but it can help you extract words. Try solving that problem first – writing a function that can take a string as input and return an array of words – and seeing if you can use the result to make it the rest of the way. – Ry- Aug 13 '20 at 06:42
  • @Ry- thanks for the suggestion, I don't know if what I am doing is correct but I split the "Central Park" string to get an array of words then loop that array and try to use regex and match the words as suggested above – Ian Santos Aug 13 '20 at 07:10
  • The first part of that sounds correct! Can you show the code you have? – Ry- Aug 13 '20 at 07:53
  • Hello @Ry sorry for the late response, please see the answer I posted, suggestions are very much welcome thank you! – Ian Santos Aug 13 '20 at 10:16

1 Answers1

0

I managed to do this based on the suggestions given but the code still feels like it can be still improved.

const places =['Central Park', 'Arches National Park', 'Bryce Canyon National Park']
const searchTerm = "Central Park"

checkIfSearchTermMatches(places, searchTerm)

function checkIfSearchTermMatches(places, searchTerm) {
  let matchedPlace = null;
  for (place of places) {
    let splitPlace = place.split(" ");
    let matchCount = 0;
    for (name of splitPlace) {
      var matchWordRegex = new RegExp(name, "i");
      const nameMatches = searchTerm.match(matchWordRegex);
      if (nameMatches && nameMatches !== null) {
        matchCount++;
      }
    }
    if (matchCount >= 2) {
      matchedPlace = place;
    }
  }
}


Ian Santos
  • 127
  • 1
  • 2
  • 11