sooraj s pillai
sooraj s pillai

Reputation: 916

Url validation regex javascript

I'm working on a URL validation using Javascript. Here I tried a regex that satisfies all my needs except one. I want to get the result false when the input is other than ".com". In the current situation it shows true for ".comm".

var a=["https://www.example.com","https://www.example.com/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share","https://www.example.commmmm/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share"];
var re=/^((https):\/\/)?(www.)[a-z0-9]+(\.(com))+(.*)?$/;
a.map(x=>console.log(x+" => "+re.test(x)));

Upvotes: 0

Views: 113

Answers (3)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You can resolve this by specifying that right after com, there can be anything starting with a slash or question mark (as it is also a valid case). Moreover, I think you should also add - to the part where you match the domain name as it is also a valid character in the domain names.

Here I have created a snippet with more test cases:

var a=["https://www.ex-ample.com", "https://www.example.com", "https://www.example.com?ala=makota","https://www.example.com/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share","https://www.example.commmmm/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share"];
var re=/^((https):\/\/)?(www.)[a-z0-9-]+(\.(com))+(\/.*|\?.*)?$/;
a.forEach(x=>console.log(x+" => "+re.test(x)));

Upvotes: 1

Naveen Chand Pandey
Naveen Chand Pandey

Reputation: 61

Hope I understood the question correctly.

Try the following regex pattern:

var re=/^((https):\/\/)?(www.)[a-z0-9]+(\.(com))+(\/.*)?$/;

var a=["https://www.example.com","https://www.example.com/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share","https://www.example.commmmm/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share"];
var re=/^((https):\/\/)?(www.)[a-z0-9]+(\.(com))+(\/.*)?$/;
a.map(x=>console.log(x+" => "+re.test(x)));

I checked your test cases and they are working fine.

Upvotes: 0

Always Learning
Always Learning

Reputation: 5591

You can do that by insisting anything after the .com start with a slash. This can be done by inserting the slash in the (.*)? part like this (\/.*)? as in the snippet below. This says "after the .com there can be either nothing or anything starting with a slash". Note that the slash needs to be escaped with a backslash.

var a=["https://www.example.com","https://www.example.com/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share","https://www.example.commmmm/hz/wishlist/ls/3LIMPQXAM4REU?ref_=wl_share"];
var re=/^((https):\/\/)?(www.)[a-z0-9]+(\.(com))+(\/.*)?$/;
a.map(x=>console.log(x+" => "+re.test(x)));

Upvotes: 1

Related Questions