views:

18

answers:

1

Hi

I wish to use the following regex for validating a file-upload:

/^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w ]*))+\.(ext)$/

But i want to be able to specify the ext filter.

Is this right?

function validateFile(str, ext) {
    alert(str);
    var expr = new RegExp("/^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w ]*))+\.(" + ext.toLowerCase() + ")$/");
    alert(expr);
    return expr.test(str);  
}
+1  A: 

You don't need to include the slashes at the start and end when you use the RegExp constructor:

var expr = /foo/;

Is equivalent to:

var expr = new RegExp("foo");

You just have to take care of double escaping backslashes (\) on the pattern string, for example:

var expr = /\\/;

Should be:

var expr = new RegExp("\\\\");

That's because in a string literal, the backslash is used also to escape characters.

Edit: The equivalent of

var expr = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w ]*))+\.(ext)$/;

Should be:

var expr = new RegExp("^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w ]*))+\\.("+
                      ext.toLowerCase + ")$");

Note that you can also use the case-insensitive flag, in the literal notation as /foo/i, with the RegExp constructor: new RegExp("foo", "i").

CMS
ok, after removing the slashes - this is what i have now - `new RegExp("^(([a-zA-Z]:)|(\{2}\w+)\$?)(\(\w[\w ]*))+\.(" + ext.toLowerCase() + ")$")`
wretrOvian
Which is again throwing an error
wretrOvian
@wretrOvian: Give a look to my edit, you need to *double* escape the slashes, not to remove them.
CMS