Reputation: 181
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
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.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
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