Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Reg Exp to match specific domain name

I have been trying to make a Reg Exp to match the URL with specific domain name.

So if i want to check if this url is from example.com what reg exp should be the best?

This reg exp should match following type of URLs:

http://api.example.com/...
http://preview.example.com/...
http://www.example.com/...
http://purhcase.example.com/...

Just simple rule, like http://{something}.example.com/{something} then should pass.

Thank you.

like image 389
Codemole Avatar asked Sep 23 '15 02:09

Codemole


2 Answers

I think this is what you're looking for: (https?:\/\/(.+?\.)?example\.com(\/[A-Za-z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;\=]*)?).

It breaks down as follows:

  • https?:\/\/ to match http:// or https:// (you didn't mention https, but it seemed like a good idea).
  • (.+?\.)? to match anything before the first dot (I made it optional so that, for example, http://example.com/ would be found
  • example\.com (example.com, of course);
  • (\/[A-Za-z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;\=]*)?): a slash followed by every acceptable character in a URL; I made this optional so that http://example.com (without the final slash) would be found.

Example: https://regex101.com/r/kT8lP2/1

like image 199
Joe DeRose Avatar answered Oct 27 '22 00:10

Joe DeRose


Use indexOf javascript API. :)

var url = 'http://api.example.com/api/url';

var testUrl = 'example.com';

if(url.indexOf(testUrl) !== -1) {
    console.log('URL passed the test');
} else{
    console.log('URL failed the test');
}

EDIT:

Why use indexOf instead of Regular Expression.

You see, what you have here for matching is a simple string (example.com) not a pattern. If you have a fixed string, then no need to introduce semantic complexity by checking for patterns.

Regular expressions are best suited for deciding if patterns are matched.

For example, if your requirement was something like the domain name should start with ex end with le and between start and end, it should contain alphanumeric characters out of which 4 characters must be upper case. This is the usecase where regular expression would prove beneficial.

You have simple problem so it's unnecessary to employ army of 1000 angels to convince someone who loves you. ;)

like image 42
AdityaParab Avatar answered Oct 26 '22 22:10

AdityaParab