Reputation: 366
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]);
};
}
};
Upvotes: 3
Views: 28559
Reputation: 966
Make a dot function and use it just like es6 includes() in es5 as below :
String.prototype.includes = function (str) {
return this.indexOf(str) !== -1;
}
Following is the string
var myString = 'this is my string';
Checking the match as following:
console.log(myString.includes('string')); // true
console.log(myString.includes('street')); //false
Now you can add this for ES5 using same indexOf in includes way
Upvotes: 0
Reputation: 62213
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.
Upvotes: 3
Reputation: 3333
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 ofindexOf
method.
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]);
};
}
};
Upvotes: 2