开发者

Regular Expression not working in JavaScript

开发者 https://www.devze.com 2023-03-16 01:40 出处:网络
This is working fine if i am writing jpg|png|jpeg|gif here... if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消