URL をパースする方法
URL をプロトコル、ホスト、ポート、パス、クエリ、フラグメントに分解します。
问题
ホスト名やクエリパラメータなど、URL の特定部分を抽出する必要があります。
前提条件
- URL 構造の理解
- URL の構成要素への習熟
ステップ
-
1. Understand URL components
A URL consists of a scheme (protocol), authority (userinfo@host:port), path, query string, and fragment. Each part is optional in certain contexts. The standard URL format is defined in RFC 3986.
入力https://[email protected]:8080/path?q=1#frag输出scheme: https, host: example.com, port: 8080, path: /path, query: q=1, fragment: frag -
2. Parse the URL
Use a URL parser rather than splitting on characters. A parser correctly handles edge cases like IPv6 addresses in brackets, encoded characters, and missing components. The WHATWG URL API is the modern standard.
入力https://example.com/path?q=1输出parsed components -
3. Extract and use components
Access the specific components you need: hostname for DNS lookups, pathname for routing, searchParams for query values. Parse query parameters into a key-value map. Handle missing components gracefully.
入力searchParams: q=1&page=2输出{q: '1', page: '2'}
期待される結果
個々の構成要素に分解され、検査や利用が可能な状態になった URL。
よくあるエラー
- Splitting on ':' or '/' instead of using a parser
- Use a proper URL parser. Naive splitting fails on IPv6 addresses, encoded slashes, and missing components.
- Query parameters not decoded
- URL-decode query parameter values after parsing. %20 should become a space, %26 should become &.
トラブルシューティング指引
- If parsing fails, the URL may be malformed or relative. Use a base URL to resolve relative URLs.
- IPv6 addresses must be in brackets: http://[::1]:8080/.
セキュリティ上の制限
- Parsed URLs may point to malicious hosts. Validate the scheme and host before making requests. Be aware of open redirect vulnerabilities.
関連ツール
URL パーサー
Parse a URL into its components: protocol, host, path, query, hash, port, username, and password。無料、プライベート、100%クライアントサイド。 ツール
URL エンコーダー
Percent-encode text for safe use in URLs。無料、プライベート、100%クライアントサイド。 ツール
URL デコーダー
Decode percent-encoded URL text back to readable characters。無料、プライベート、100%クライアントサイド。 ツール