Setting url.pathname = 'newpath' normalizes the path by adding a leading slash, resulting in '/newpath'.
Step 2: Construct the full URL
Hostname changes to 'newsite.com', port to '3000', pathname becomes '/newpath'. So full URL is 'https://newsite.com:3000/newpath'.
Final Answer:
https://newsite.com:3000/newpath -> Option B
Quick Check:
Pathname setter normalizes with leading '/' [OK]
Hint: pathname setter adds leading '/' automatically [OK]
Common Mistakes:
Expecting '//newpath' without leading slash
Assuming pathname auto-adds slash
Confusing pathname with href
5. You want to change the query parameter id to 42 in this URL: https://shop.com/products?category=books&id=10. Which code correctly updates the URL using the URL class?
hard
A. const url = new URL('https://shop.com/products?category=books&id=10');
url.searchParams.set('id', '42');
console.log(url.href);
B. const url = new URL('https://shop.com/products?category=books&id=10');
url.query.id = 42;
console.log(url.href);
C. const url = new URL('https://shop.com/products?category=books&id=10');
url.search.id = '42';
console.log(url.href);
D. const url = new URL('https://shop.com/products?category=books&id=10');
url.setQuery('id', '42');
console.log(url.href);
Solution
Step 1: Identify how to update query parameters
The URL class provides searchParams with methods like set() to update query parameters safely.
Step 2: Check each option's method
const url = new URL('https://shop.com/products?category=books&id=10');
url.searchParams.set('id', '42');
console.log(url.href); uses searchParams.set(), which is correct. Options A, C, and D use invalid properties or methods not available on URL objects.
Final Answer:
const url = new URL('https://shop.com/products?category=books&id=10');
url.searchParams.set('id', '42');
console.log(url.href); -> Option A
Quick Check:
Use searchParams.set() to update query [OK]
Hint: Use url.searchParams.set() to change query values [OK]