user2345351 user2345351 - 2 months ago 13
Javascript Question

Checking if a string contains any part of an array element

I just started learning javascript and I'm working on small chrome extension that checks a certain website's item listings for any items
that contain keywords provided by the user. I'm looking for some help on a method to compare a string to an array of strings.

So I have these variables:

var itemDetails = '[alter] saber 1/8 figure unopened';
var trackingList = ['alter figure', 'magic', 'sword art'];


I need to check if itemDetails contains any of the strings in trackingList. I know I can use
indexOf()
like this:

function checkArray(str, arr){
for(var i=0; i < arr.length; i++){
if(str.indexOf(arr[i]) > -1)
return true;
}
return false;
}

checkArray(itemDetails,trackingList); // returns false


However, for strings with multiple words in them, such as 'alter figure', I want
checkArray()
to return true as long as both of the words in the string appear anywhere in
itemDetails
. So
checkArray()
should return true in the example above since both 'alter' and 'figure' are in
itemDetails
.

The method I'm currently using is to split each element in
trackingList
:

function splitTrackList(arr){
var newarr = [];
for(var i = 0; i < arr.length; i++){
newarr[i] = arr[i].split(" ");
}
return newarr;
}

trackList = splitTrackList(trackList);
// [['alter', 'figure'], ['magic'], ['sword', 'art']]


And then compare using
indexOf()
:

function newCheckArray(str, arr){
var passed = true;
for(var i=0; i < arr.length; i++){
for(var j=0; j < arr[i].length; j++){
if(str.indexOf(arr[i][j]) == -1){
passed = false;
break;
}
else passed = true;
}

if(passed) //stop loop if match found
break;
}
return passed;
}

newCheckArray(itemDetails,trackingList); //returns true


My method works so far but I'm guessing there is a much faster/efficient way of doing this. Please let me know what you think. Thank you in advance.

Answer

You can use regular expressions. I am giving you an example, although it is not the most efficient

function checkArray(str, arr){
   for(var i=0; i < arr.length; i++){
       if(str.match((".*" + arr[i].trim() + ".*").replace(" ", ".*")))
           return true;
   }
   return false;
}

Here I alter the string "key1 keyn" to ".*key1.keyn." so it could match those keys everywhere in the string. Have in mind that this will match them if they are part of another word. Good luck.

P.S. Learn regular expressions. They are pretty important in almost every language.