lgriffin
lgriffin

Reputation: 197

Find all matches in string with regex in any order with Javascript

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

Upvotes: 0

Views: 1296

Answers (3)

Abilio Da Silva
Abilio Da Silva

Reputation: 43

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

Upvotes: 0

0stone0
0stone0

Reputation: 43998

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

Upvotes: 2

Anirudha
Anirudha

Reputation: 32797

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", ""]

Upvotes: 0

Related Questions