I'm trying to develop a method to match words in array (fItems) with words from a string which has been converted into an Array (stringArray). The code I have below works most the time, but the trouble is that 'includes()' searches for patterns, rather than matching the whole word.
As an example. it gets confused if I'm looking for 'wall', and it returns 'wallet'. Also, I want the input to be flexible. So for instance, if glass is inputted, the item 'glass shard' is still returnable.
Is there are more precise way to match exact words?
for (let i = 0; i < db.items.length; i++) {
for (let j = 0; j < stringArray.length; j++) {
if (db.items[i].name.includes(stringArray[j])) {
fItems.push(db.items[i]);
};
}
};
from comment
No, not a straight comparison. I want the input to be flexible. So for instance, if glass is inputted, the item 'glass shard' is still returnable.
It sounds like what you are really after is pattern matching in a string. A regular expression would be the best thing to use for that as this is why they were created (pattern matching with the option of replacement).
let str = 'The glass shard';
let search = 'glass';
let isMatch = new RegExp('\\b'+search+'\\b', 'i').test(str); // i is case insensitive
// If you use unicode characters then this might be a better expression
// thank you @Touffy
let isMatch = new RegExp('(?:^|\\s)'+search, 'i').test(str); // i is case insensitive
In the code above \b is used to denote a word boundary so glass is a match but glassware would not be matched. i is used to specify case insensitive.
Also to test your expressions online before you place them in your code you can use this site https://regex101.com/, I use this all the time to verify the expressions I build are accurate.
I think you can use split and indexOf methods instead of it. After split, you can check it with indexOf.
From Comment: As Pavlo said, also you can use
includes, instead ofindexOfmethod.
for (let i = 0; i < db.items.length; i++) {
for (let j = 0; j < stringArray.length; j++) {
if (db.items[i].name.split(' ').indexOf(stringArray[j])!==-1) {
fItems.push(db.items[i]);
};
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With