user3816152
user3816152

Reputation: 257

Regular Expression wrong match

I am trying a regex to validate an Url.

var url = "https://www,google.com";
var urlRegex = /(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?/i;
var result = urlRegex.test(url);

so i am getting "result" as true but i should get false as "url" contains comma. Kindly help.

Upvotes: 1

Views: 83

Answers (2)

Andie2302
Andie2302

Reputation: 4887

You are getting true since your regex partly matches.

Use ^(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?$

instead.

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Add anchors (^ for beginning of a string, and $ for the end of the string):

^(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?$
^                                                                                                ^

See demo

Upvotes: 2

Related Questions