Javascript: RegExp object creation problem
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);
}
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")
.
精彩评论