I misunderstood at first so have ended up coming up with two options. One that searches with OR i.e. if any of the words match then found.
And one that matches with for AND, which is what I think you want. (unfortunately there isn’t an && in javascript regular expressions)
Search to see if any of the words come up.
function multiSearchOr(text, searchWords){
// create a regular expression from searchwords using join and |. Add "gi".
// Example: ["ANY", "UNATTENDED","HELLO"] becomes
// "ANY|UNATTENDED|HELLO","gi"
// | means OR. gi means GLOBALLY and CASEINSENSITIVE
var searchExp = new RegExp(searchWords.join("|"),"gi");
// regularExpression.test(string) returns true or false
return (searchExp.test(text))?"Found!":"Not found!";
}
console.log(multiSearchOr("Any items left unattended on this table", ["ANY","UNATTENDED","HELLO"])); // Found!!
console.log(multiSearchOr("Any items left unattended on this table", ["apple","orange","strawberry"])); // Not Found!!
Search to see if all the words come up.
function multiSearchAnd(text, searchWords){
// create a regular expression from searchwords using join and |. Add "gi".
// this time put our search words inside back reference catching brackets
// Example: ["ANY", "UNATTENDED","HELLO"] becomes
// "(ANY)|(UNATTENDED)|(HELLO)","gi"
// (..) are backreferences. | means OR. gi means GLOBALLY and CASEINSENSITIVE
var searchExp = new RegExp("("+searchWords.join(")|(")+")","gi");
// use match to return an array of backreference matches. If the array length doesn't match searchWords then Not found!!
return (text.match(searchExp).length == searchWords.length)?"Found!":"Not found!";
}
console.log(multiSearchAnd("Any items left unattended on this table", ["ANY","UNATTENDED","hello"])); // Not Found!!
console.log(multiSearchAnd("Any items left unattended on this table", ["Any","UNattended","taBle"])); // Found!!
The 2 functions uncommented
function multiSearchOr(text, searchWords){
var searchExp = new RegExp(searchWords.join("|"),"gi");
return (searchExp.test(text))?"Found!":"Not found!";
}
function multiSearchAnd(text, searchWords){
var searchExp = new RegExp("("+searchWords.join(")|(")+")","gi");
return (text.match(searchExp).length == searchWords.length)?"Found!":"Not found!";
}
edit: The multiSearchAnd is flawed. If you have multiple matches like
multiSearchAnd(“Any items left unattended on any table”, [“ANY”,“UNATTENDED”,“hello”])
it will return found!!
will work on a solution
RLM