We all know that regExp can match two strings using a common word in both strings as criterion for the match. This code will match "I like apples" to "apples" because they both have "apples" in common.
var str1 = "apples";
var test1 = "I like apples";
var reg1 = new RegExp(str1, "i");
if (test1.match(reg1)) {
console.log(str1 + " is matched");
}
But what if instead of matching the strings using a single common word (or a common part of the strings), I need to match the two strings using multiple common words which may be separated by other words ? Let me show you an example :
test2 = "I like juicy red fruits" should match str2 = "juicy fruits" because test2 contains all of str2 second key words (see object bellow), even though it has other words inbetween.
Tricky part is that I can't know exaclty what one the strings will be, so I have to match them dynamically. The string I don't know is the value of a user input field, and there are many possibilities. This value is to be matched to the strings stored in this object :
var str2 = {
"red apples": "fruits",
"juicy fruits": "price : $10"
};
So whatever the user types in the input field, it must be a match if and only if it contains all the words of one of the object properties. So in this example, "juicy red and ripe fruits" should match the second object property, because it contains all of its keywords.
Edit : My goal is to output the value associated to the strings I'm matching. In my example if the first key is matched, 'fruits' should be output. If 'juicy fruits' is matched, it should output 'price : $10'. Getting the strings associated to the object keys is the reason why the user has to search for them using the input.
Is it possible to do this with regExp using pure javascript ?
Here is what I (poorly) tried to do : https://jsfiddle.net/Hal_9100/fzhr0t9q/1/
(?=.*\bjuicy\b)(?=.*\bfruits\b)str2is an object that has"red apples"and"juicy fruits"as keys.test2only has"juicy", "red", and "apples". I don't understand the claim that, "test2contains all ofstr2words...". What am I misunderstanding?test2contains of allstr2second key words. I edited my post, thanks for pointing it out.str2object? That part is still unclear to me. Is this data structure really necessary?