Regular Expression not working in JavaScript
This is working fine if i am writing jpg|png|jpeg|gif here...
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
alert('E开发者_如何学Crror: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
If i use variable instead of static then it is not working
var Extensions = "jpg|png|jpeg|gif";
if (!(ext && /^(Extensions)$/.test(ext))) {
alert('Error: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
Thanks in advance Imdadhusen
You should do it like this:
(new RegExp("jpg|png|jpeg|gif")).test(ext)
You are using invalid syntax for the regular expression. If you are going to store it in a variable, you must still use your regular expression from your first example.
So:
var Extensions = /^(jpg|png|jpeg|gif)$/;
if (!(ext && Extensions.test(ext)))
will work. Your second example is trying to match the word 'Extensions'.
it wont get error
var Extensions = "/^(jpg|png|jpeg|gif)$/";
if (!(ext && Extensions.test(ext))) {
alert('Error: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
To use a variable, you need to use the RegExp object:
new RegExp('^(' + Extensions + ')$').test(ext)
Or assign the entire regex into your variable:
var Extensions = /^(jpg|png|jpeg|gif)$/;
Extensions.test(ext)
Perhaps call it allowedExtensions or something though.
Try this:
var Extensions = /^(jpg|png|jpeg|gif)$/;
if (!(ext && Extensions.test(ext))) {
alert('Error: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
精彩评论