Chris Cullen
Chris Cullen

Reputation: 110

Regex Match ALL Dynamic string words to data attribute

Is it possible to have a dynamically generated string

var string= "a,b,c";

and make a regex out of that that accepts any of the strings words as accepted matches?

regExApproved = new RegExp(string, 'ig');

So that we can search a data-attribute of an element and show it if it has any of the accepted matches in the attribute

$(this).attr("data-payment").match(regExApproved)

The problem im facing is the regex takes the whole string and makes that the only match case.
I need the regex to break the string down and accept ANY word in it as a match

Is this possible? I do not want to use a forloop and make LOTS of different regex Matches for each word in the string but maybe I have to?

Upvotes: 4

Views: 825

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

I suggest using

var regExApproved = new RegExp(string.split(",").map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'), 'i');

Then, to check if a regex matches a string, it makes more sense to use RegExp#test method:

regExApproved.test($(this).attr("data-payment"))

Notes:

  • .split(",") - splits into comma-separated chunks
  • .map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')) (or .map(function(x) return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); })) - escapes the alternatives
  • .join('|') creates the final alternation pattern.

Edit

It seems that your string is an array of values. In that case, use

var string= ['visa','mastercard'];
var regExApproved = new RegExp(string.join('|'), 'i');
// If the items must be matched as whole words:
// var regExApproved = new RegExp('\\b(?:' + string.join('|') + ')\\b', 'i');
// If the array items contain special chars:
// var regExApproved = new RegExp(string.map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'), 'i');
console.log(regExApproved.test("There is MasterCard here"));

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

If your string is a list of comma-separated words, you can split it by comma then use a combination of Array methods to check if any word is matched inside the test string.

This is how should be your code:

string.split(",").map(s => new RegExp('\\b' + s + '\\b')).some(r => $(this).attr("data-payment").match(r))

Where we have:

  • string.split(",") to split the string by comma.
  • .map(s => new RegExp('\\b' + s + '\\b')) to return a relevant regex for each word in the string using word-boundary.
  • .some(r => $(this).attr("data-payment").match(r)) to check if our string matches any one of the created regexes.

Demo:

var string = "is,dog,car";

let str = "this is just a test";

if (string.split(",").map(s => new RegExp('\\b' + s + '\\b')).some(r => str.match(r))) {
  console.log("Matched");
}

Upvotes: 1

Related Questions