ogk
ogk

Reputation: 622

use regex to match a string with an array

I created a regex with the string I am searching for by:

var re = new RegExp(searchTerm, "ig");

And i have an array that I want to search through that has these terms:

var websiteName = [
  "google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana",
  "slack", "soundcloud", "reddit", "uscitp", "facebook"
];

If my search term is reddit testtest test, I would not get a match when I call the match function:

  for(var i = 0; i < websiteName.length; i = i + 1) {
    if(websiteName[i].match(re) != null) {
      possibleNameSearchResults[i] = i;
    }
  }

How can i structure my regex statement so that when I search through my array that it will still return true if just one of the words match?

Upvotes: 3

Views: 253

Answers (1)

Nathan Friend
Nathan Friend

Reputation: 12814

I think you want something like this:

var searchTerm = 'reddit testtest test';

var websiteNames = ["google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana", "slack", "soundcloud", "reddit", "uscitp", "facebook"];

// filter the websiteNames array based on each website's name
var possibleNameSearchResults = websiteNames.filter(function(website) {

  // split the searchTerm into individual words, and
  // and test if any of the words match the current website's name
  return searchTerm.split(' ').some(function(term) {
    return website.match(new RegExp(term, 'ig')) !== null;
  });
});

document.writeln(JSON.stringify(possibleNameSearchResults))

Edit: If you want the index instead of the actual value of the item, you are probably better off going with a more standard forEach loop, like this:

var searchTerm = 'reddit testtest test',
    websiteNames = ["google", "youtube", "twitter", "medium", "amazon", "airbnb", "campaiyn", "uber", "dropbox", "asana", "slack", "soundcloud", "reddit", "uscitp", "facebook"],
    possibleNameSearchResults = []

// loop over each website name and test it against all of
// the keywords in the searchTerm
websiteNames.forEach(function(website, index) {
  var isMatch = searchTerm.split(' ').some(function(term) {
    return website.match(new RegExp(term, 'ig')) !== null;
  });
  
  if (isMatch) {
    possibleNameSearchResults.push(index);
  }
})

document.writeln(JSON.stringify(possibleNameSearchResults))

Upvotes: 3

Related Questions