LoginSignup
1
0

More than 1 year has passed since last update.

URLからホスト名やクエリ文字列を取得する

Posted at

url.png

URL

URL - Web API | MDN

let url = new URL("https://site.com:4097/URL/index.html?d1=1&d2=2#item");
プロパティ
url.href https://site.com:4097/URL/index.html?d1=1&d2=2#item
url.origin https://site.com:4097
url.host site.com:4097
url.protocol https:
url.hostname site.com
url.port 4097
url.pathname /URL/index.html
url.search ?d1=1&d2=2
url.hash #item
url.username
url.password
url.searchParams URLSearchParams オブジェクトを返す。

ポート番号がスキームのデフォルトポートの場合

TCPやUDPにおけるポート番号の一覧 - Wikipedia

//443はhttpsのデフォルトポート
let url = new URL("https://site.com:443/URL/index.html");
プロパティ
url.href https://site.com/URL/index.html
url.origin https://site.com
url.host site.com
url.port

URLSearchParams

URLSearchParams - Web API | MDN

//サイトURL:https://site.com:4097/URL/index.html?d1=1&d2=2
let searchParams = new URLSearchParams(window.location.search);
メソッド 内容
searchParams.has("d1") パラメータの有無 true
searchParams.get("d1") パラメータの値の取得 1
searchParams.set("d3",4) パラメータd3に4を設定
searchParams.delete("d1") パラメータの削除
searchParams.toString() クエリ文字列作成 d2=2&d3=4
Object.fromEntries(searchParams) オブジェクトに変換 { d2: "2", d3: "4" }

その他のメソッド entriesforEachkeysvaluesappendgetAllsort

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0