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.
Code
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
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Nano ID GeneratorGenerate URL-safe Nano ID strings with a configurable length and alphabet using the Web Crypto API.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.