I want to perform what should be a simple search on a string to see if it contains all of several search terms, in a case insensitive manner.
For example, "The quick brown fox" contains the words "fox" and "quick", so I want a function which can take those two words and show that the phrase contains them both, regardless of their order.
So I guess what I'm asking for is a string-based "AND" search.
A simple solution is to use the array.every()
method to check that every search term is included in a string.
I'm specifying the search terms as a single string, which will be split by spaces:
var haystackString = "The quick brown fox";
var needleString = "fox quick";
var searchTerms = needleString.split(" ");
return searchTerms.every(function stringContains(element, index, array) {
return haystackString.toUpperCase().includes(element.toUpperCase());
});
The above will return true
.
Be aware that toUpperCase()
might not work with all languages.
Convert the array of terms to a RegExp . Then use use String#match to find all matches in string. If the number of matches is identical to the number of terms, it contains all of them:
var str = 'The quick brown fox'; function containsAll(str, terms) { var regexp = new RegExp(`\\\\b(${terms.join('|')})\\\\b`, 'gi'); var matches = str.match(regexp); return matches !== null && matches.length === terms.length; } console.log(containsAll(str, ['fox', 'quick'])); console.log(containsAll(str, ['cat', 'quick']));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.