In node.js how to get/construct URL string from WH

2019-09-20 11:57发布

What would be the recommended way of deriving the following:

https://user:pass@hostname:port

From:

https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash

when dealing with node.js url module using current WHATWG URL ?

2条回答
太酷不给撩
2楼-- · 2019-09-20 12:22

As of Node 8.x with the WHATWG URL API:

const { URL } = require('url');
const url = new URL('https://user:pass@hostname:1234/p/a/t/h?q=whatevere#hash');
url.search = url.pathname = url.hash = '';
console.log(url.toString()); // https://user:pass@hostname:1234/
查看更多
爷、活的狠高调
3楼-- · 2019-09-20 12:29

Pretty sure you can use standard javascript with node.js

  var s = 'https://user:pass@hostname:port/path#hash';
  s = s.substring(0, s.lastIndexOf('/'));

That should give you s as the value you want.

Caz

Update -

You could also do this if you can't predict the number of / in the URL

var url = 'https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash';
url = url.split( '/' )[2];

What that does is creates an array from that string using / as the deliminator. So url[0] would be https: url[1] would be blank as its between the two / and url[2] will be user:pass@hostname:port

So if you don't need the http part you can do that and even do something like this is the https is important

var url = 'https://user:pass@hostname:port/p/a/t/h?q=whatevere#hash';
url = url.split( '/' )[2];
var urlstring = 'https://' + url 
查看更多
登录 后发表回答