Reputation: 579
Let's say I have an object called options. Inside the object, I have one key named imageTypes. I am trying to test if png matches any one of the imageTypes. What am I doing wrong here. Thanks for the input guys!
var options = {
imageTypes: /\.(gif|jpe?g|png)$/i
}
if (options.imageTypes.test(image/png)) {
//do stuff
}
Upvotes: -1
Views: 97
Reputation: 7018
Hope this will help you understand what you are trying to achieve: http://jsfiddle.net/pratik136/YZ5ZD/
var options = {
imageTypes1: /\.(gif|jpe?g|png)$/i,
imageTypes2: /image\/(gif|jpe?g|png)$/i
};
if (options.imageTypes1.test('.png')
&& options.imageTypes2.test('image/png')) {
//do stuff
showResult('true');
} else {
showResult('false');
}
imageTypes1
is a Regex that will match a string like .png
, while imageTypes2
is trying to match image/png
The syntax error in your code sample is the missing quotes around image/png
, while the logical error is that you are using the wrong Regular Expression.
Upvotes: 0
Reputation: 1373
If you want to test "image/png" as a string, then you'll have to change your regex as it now checks for the image extension in a dot format.
var options = {
imageType: function(pic) {
return (/^image\/(gif|jpe?g|png)$/i).test(pic);
}
};
// returns true
console.log(options.imageType('image/png'));
Upvotes: 0
Reputation: 5382
You're using a math operation (i.e. division) before you're calling test. This will result in the RegEx being called over a number, which doesn't really work that well.
If image is a variable of yours, drop the /png
. Or if you're trying to compare 'image/png' (i.e. the string), then you will have to enter the quotes before and after.
Tested it out on jsFiddle here, you can find the results in the console output.
Upvotes: 1