javascript Reg Exp to match specific domain name

前端 未结 6 2125
小鲜肉
小鲜肉 2021-01-12 09:34

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 bes

6条回答
  •  忘掉有多难
    2021-01-12 10:06

    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!

提交回复
热议问题