Reputation: 507
I am trying to change the pathname and protocol of window.location.href
, to a new string.
const getUrl = new URL(window.location.href); //'https://example.com/questions'
I'm trying to create a new variable from the above, so it becomes:
'https://api.example.com/parameter'
I can see in here I have access to the pathname and protocol, which are the bits I want to change, but how do I actually change them? My attempt:
const newURL = getURL
.replace(getURL.protocol, 'https://api')
.replace(getURL.pathname, '/parameter');
However, with this I get an error like 'VM825:1 Uncaught TypeError: getURL.replace is not a function'
. Can anybody help?
Upvotes: 2
Views: 3777
Reputation: 467
The getURL
variable contains an object you can modify, so changing its host
and pathname
, you can obtain the URL you mentioned. You can see a demo below:
const url = new URL(window.location.href); // https://example.com/questions
url.host = "api.example.com";
url.pathname = "/parameter";
const href = url.href; // https://api.example.com/parameter
console.log(href);
Upvotes: 4