0

How can i find all matches below? The way i've got it now, it finds finds any match from the keywords array, but, since the word "not" is present, matches should be empty in the console.

var title = "How to edit an image";
var keywords = ["image","edit","not"];
var matches = [];
if (title.search(new RegExp(keywords.join("|"),"i")) != -1) {
     matches.push(title);
}
console.log(matches);
Mitya
  • 33,629
  • 9
  • 60
  • 107
lgriffin
  • 177
  • 2
  • 12

3 Answers3

2

No need for the regex, just loop through the words using every() , and check each keyword using includes() (See below);

console.log(Check("How to edit an image", ["image","edit","not"])); // false
console.log(Check("How to edit an image", ["image","edit"]));       // true

function Check(title, keywords) {
    return keywords.every(word => title.indexOf(word) > -1);
}

Note: Using title.indexOf(word) > -1 to support IE 11 as OP requested.


Edit; based on OP's comment;

Remove "not" from the keywords array to ensure the logic works

var title = "How to edit an image";
var keywords = ["image","edit","not"];
var matches = [];
if (keywords.every(word => title.indexOf(word) > -1)) {
     matches.push(title);
}
console.log(matches);
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • I don't know how to incorporate this into my logic, sort of struggling here, can you combine your code to my post above, with no arrow function – lgriffin Feb 05 '21 at 15:19
  • 0stone0, you are still using arrow functions! – sxkx Feb 05 '21 at 16:43
  • I changed it a bit to remove that: function findMatch(title, keywords) { return keywords.every(function(word) { return title.indexOf(word) > -1; }) } – lgriffin Feb 05 '21 at 16:48
0

You dont need regex. Just map over keywords

const output= keywords.map(x=>
    title.indexOf(x)!==-1 ? title : ""
);

//output
["How to edit an image", "How to edit an image", ""]
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

Using this answer as a reference, and olny if you are fixed to use Regex, you should use lookarounds:

^(?=.*\bimage\b)(?=.*\bedit\b)(?=.*\bnot\b).*$

Applied on your Javascript code it would be something like:

var title = "How to edit an image";
var title2 = "How to not edit an image";
var keywords = ["image","edit","not"];
var matches = [];

// Using for block because I don't remember if forof, forin or foreach are supported by IE 11
var regex = "^";
for (var i = 0; i < keywords.length; i++) {
    regex += "(?=.*\\b" + keywords[i] + "\\b)"; // Needed beacuse template Strings are not supported by IE 11.
}
regex += ".*$"

if (title.search(new RegExp(regex,"i")) != -1) {
    matches.push(title);
}
console.log(matches);

if (title2.search(new RegExp(regex,"i")) != -1) {
    matches.push(title2);
}
console.log(matches);
  • 1
    To say the true, @0stone0 answer is a lot better on terms of use. I posted this solution only if you really want to use regular expressions. – Abilio Da Silva Feb 05 '21 at 15:55