1

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

vajehu
  • 181
  • 1
  • 2
  • 10

2 Answers2

3

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);
})
guest271314
  • 1
  • 15
  • 104
  • 177
  • Note that `.` matches any character. So If the filename was `opngate.gif`, it would match `.png`. You have to escape the `.` properly. – Felix Kling Oct 12 '17 at 16:18
  • @FelixKling `opngate.gif` would not be matched using the pattern at Answer though you do have a point, see updated post. – guest271314 Oct 12 '17 at 16:21
  • 1
    Run ``"opngate.gif".match(new RegExp(`.png`, "i"))`` in your console ;) – Felix Kling Oct 12 '17 at 16:22
  • @FelixKling You are correct. Ran test improperly. Was also missing `$` within `RegExp`. `[.]${pattern}` could alternatively be used. – guest271314 Oct 12 '17 at 16:24
3

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143