Javascript 如何使用本机URL构造和操作URI?

Javascript 如何使用本机URL构造和操作URI?,javascript,Javascript,支持使用以下内容构造URL: new URL('https://example.com/path/to/resource?query=param#hash') new URL('/path/to/resource?query=param#hash', 'https://example.com') 我的URI/path/to/resource?query=param#hash没有基本url 我对URI的使用与URL完全相同。我可以利用本机URL做我想做的事情吗?基本上,我想: // create

支持使用以下内容构造URL:

new URL('https://example.com/path/to/resource?query=param#hash')
new URL('/path/to/resource?query=param#hash', 'https://example.com')
我的URI
/path/to/resource?query=param#hash
没有基本url

我对URI的使用与URL完全相同。我可以利用本机URL做我想做的事情吗?基本上,我想:

// create a URI /path/to/resource
// set query parameters
// set hash
// return entire URI as string /path/to/resource?query=param#hash

如果没有,我将不得不使用外部库,如。

这不是最好的方法,但如果您坚持使用,您可以执行以下操作:

const yourUrl=newURL('/path/to/resource?query=param#hash','https://example.com')
console.log(yourUrl.href.replace(yourUrl.origin,”)