javascript Reg Exp to match specific domain name

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. ;)


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


Not sure if this would work for your case, but it would probably be better to rely on the built in URL parser vs. using a regex.

var url  = document.createElement('a');
url.href = "http://www.example.com/thing";

You can then call those values using the given to you by the API

url.protocol // (http:)
url.host     // (www.example.com)
url.pathname // (/thing)

If that doesn't help you, something like this could work, but is likely too brittle:

var url     = "http://www.example.com/thing";
var matches = url.match(/:\/\/(.[^\/]+)(.*)/);

// matches would return something like
// ["://example.com/thing", "example.com", "/thing"]

These posts could also help:

https://stackoverflow.com/a/3213643/4954530

https://stackoverflow.com/a/6168370

Good luck out there!


Use this:

/^[a-zA-Z0-9_.+-]+@(?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)?
(domain|domain2)\.com$/g

To match the specific domain of your choice.

If you want to match only one domain then remove |domain2 from (domain|domain2) portion.

It will help you. https://www.regextester.com/94044