new URL Breaks A Location Into Parts

new URL splits scheme, host, port, path, and hash without string surgery, while searchParams.get, set, and append keep every mutation URL-safe.

JavascriptData Fetching

Code

javascriptsnippet
18 lines
const url = new URL(
  "https://api.example.com:8443/v2/search?q=red&page=2&tag=a&tag=b#top",
);

console.log("protocol :", url.protocol);
console.log("host     :", url.host);
console.log("port     :", url.port);
console.log("pathname :", url.pathname);
console.log("hash     :", url.hash);
console.log("origin   :", url.origin);

// searchParams 是 URLSearchParams:读取、遍历、追加都简单
console.log("q        :", url.searchParams.get("q"));
console.log("tags     :", url.searchParams.getAll("tag"));

url.searchParams.set("page", "3");
url.searchParams.append("lang", "en");
console.log("next     :", `${url.pathname}${url.search}${url.hash}`);

What the code does

Demo state sits in top-level bindings: url.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Applying it

The file announces its steps in the output: protocol :, host :, port :.

Statements that matter

url.searchParams.append("lang", "en");
url.searchParams.set("page", "3");

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `url`.