Which code correctly builds this URL with proper encoding?
hard📝 state output Q15 of 15
Node.js - URL and Query String Handling
You want to build a URL with base 'https://api.example.com/search' and add parameters 'query' with value 'node.js tips' and 'sort' with value 'recent'. Which code correctly builds this URL with proper encoding?
Use new URL with base URL, then append parameters with searchParams.append to add multiple values safely.
Step 2: Check encoding and method correctness
const url = new URL('https://api.example.com/search');
url.searchParams.append('query', 'node.js tips');
url.searchParams.append('sort', 'recent');
console.log(url.href); uses append correctly and prints href, which includes proper encoding of spaces as '%20'. const url = new URL('https://api.example.com/search');
url.searchParams.set('query', 'node.js tips');
url.searchParams.set('sort', 'recent');
console.log(url.toString()); uses set which replaces values but also works; however, question asks for correct code with proper encoding and append is more common for adding multiple params. const url = 'https://api.example.com/search?query=node.js tips&sort=recent';
console.log(url); is manual string and misses encoding. const url = new URL('https://api.example.com/search');
url.searchParams.add('query', 'node.js tips');
url.searchParams.add('sort', 'recent');
console.log(url.href); uses non-existent 'add' method.
Final Answer:
Option C code correctly builds URL with proper encoding and appends parameters. -> Option C
Quick Check:
Use URL + searchParams.append for safe, encoded URLs [OK]
Quick Trick:Use URL and searchParams.append for safe, encoded query parameters [OK]
Common Mistakes:
Manually concatenating query strings without encoding
Using non-existent 'add' method
Ignoring encoding of spaces and special characters
Master "URL and Query String Handling" in Node.js
9 interactive learning modes - each teaches the same concept differently