Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  105] [ 6]  / answers: 1 / hits: 19176  / 7 Years ago, fri, february 10, 2017, 12:00:00

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]);
};
}
};




More From » arrays

 Answers
95

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.


[#58988] Wednesday, February 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;