check if the string is a combination of strings in a array using javascript

Viewed 589

I have a requirement to check if a string is formed with any combination of strings given in a array example : we have array of ["for","car","keys","forth"] and a string of "forthcarkeys", the result should be true.If the string is "forthcarxykeys", the result should be false as xy is not in the array. Order of words in array doesnt matter. its not necessary that all strings from array should be matched but the teststring should only be made of any of the strings in array. If it contain any string other than the ones in array, return false

my approach:

var str = "forthcarkeys";
var arr = ["for","car","keys","forth"];
for(var i=0;i<arr.length;i++)
{
   if(str.indexOf(arr[i]) !== -1)
   {
      str.replace(arr[i],"");
   }
}

if(str !== "")
{
  console.log("yes");
} else 
{
  console.log("no");
}

but this approach is not efficient and failing.

7 Answers
Related