开发者

How do I resolve an "invalid quantifier" error with regexp in javascript?

开发者 https://www.devze.com 2022-12-13 06:34 出处:网络
I\'m trying to transfer the following URL validation function from my PHP code to my javascript code:

I'm trying to transfer the following URL validation function from my PHP code to my javascript code:

   this.v开发者_JAVA技巧alidate_url = function(field)
    {
        var pattern = new RegExp("^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?");
        var val = $("#" + field).val();

        return pattern.test(val);
    }

And this gives me the error:

invalid quantifier ?w+=w+)?(&w+=w+)*)?

How can I fix this?


You either need to escape the backslashes within the string declaration:

var pattern = new RegExp("^((ht|f)tp(s?)://|~/|/)?(\\w+:\\w+@)?([a-zA-Z]{1}([\\w-]+\\.)+(\\w{2,5}))(:\\d{1,5})?((/?\\w+/)+|/?)(\\w+\\.\\w{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?");

Or you use the regular expression literal syntax /expr/flags:

var pattern = /^((ht|f)tp(s?):\/\/|~\/|\/)?(\w+:\w+@)?([a-zA-Z]{1}([\w-]+\.)+(\w{2,5}))(:\d{1,5})?((\/?\w+\/)+|\/?)(\w+\.\w{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?/;

You should also try to use non-capturing groups (?:expr) where you don’t need to reference the match of that groups.


Since backslash is an escaping character in JavaScript, you'll have to escape that to write it in a string:

var pattern = new RegExp("^((ht|f)tp(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.[\\w]{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?");
0

精彩评论

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