vajehu
vajehu

Reputation: 181

Match regex using array

I made this in C++ and I wanted to convert to JavaScript:

foreach (QString pattern, extensions) {
    regex.setPattern(QString("\\.%1").arg(pattern));
    regex.setPatternOptions(QRegularExpression::CaseInsensitiveOption);

    QRegularExpressionMatch match = regex.match(filename);

    if (! match.hasMatch()) continue;

    return pattern;
}

It means that foreach extensions (that is an array of extensions) as pattern create a pattern with that to be like: \\.png (for example). If there's a match it will return the found extension.

I tried to create exactly how I did in C++ but I don't know how to concatenate the returned string from the array to match

const filename = 'example.wutt'
const extensions = ['wutt', 'xnss']

extensions.forEach(pattern => {
  const match = filename.match(`\\.${pattern}`)
  console.log(match)
})

It does work but it's not case-insensitive as I can't put the i flag.

How can I do that (and if there's a solution using ES6)?

Upvotes: 1

Views: 3300

Answers (2)

Felix Kling
Felix Kling

Reputation: 817238

Have a look at How do you use a variable in a regular expression? for building the regex.

If you want to find the extension that matches, you can use Array#find:

const matchedExtension = extensions.find(
  ext => new RegExp(String.raw`\.${ext}$`, 'i').test(filename)
);

var extensions = ['png', 'jpeg'];

var filename = 'foo.png';

console.log(extensions.find(
  ext => new RegExp(String.raw `\.${ext}$`, 'i').test(filename)
));

Couple of notes:

  • String.raw is necessary to not treat \. as a string escape sequence but to pass it "as is" to the regular expression engine (alternative you could escape the \, but String.raw is cool).
  • $ at the end of the pattern ensures that the pattern is only matched at the end of the file name.
  • If you just want to know whether a pattern matches or not, RegExp#test is the preferred method.

If you are doing this a lot it makes sense to generate an array of regular expressions first (instead of creating the regex every time you call the function).

Upvotes: 3

guest271314
guest271314

Reputation: 1

You can use RegExp constructor with "i" passed as second argument

extensions.forEach(pattern => {
    const match = filename.match(new RegExp(`\\.${pattern}$`, "i"));
    console.log(match);
})

Upvotes: 3

Related Questions