How to extract the host from a URL in JavaScript?

后端 未结 5 2113
我寻月下人不归
我寻月下人不归 2021-02-12 18:20

Capture the domain till the ending characters $, \\?, /, :. I need a regex that captures domian.com in all of these.

domain.com:3000
do         


        
5条回答
  •  太阳男子
    2021-02-12 18:40

    Since you're using node, just use the built-in url.parse() method; you want the resulting hostname property:

    var url=require('url');
    var urls = [
      'http://domain.com:3000',
      'http://domain.com?pass=gas',
      'http://domain.com/',
      'http://domain.com'
    ];
    

    UPDATED:

    urls.forEach(function(x) {
      console.log(url.parse(x).hostname);
    });
    

提交回复
热议问题