JavaScriptで文字列のURLからドメイン名とか取得するとき

JavaScriptで文字列のURLからドメイン名とか取得する

https://example.com/piyo/?hoge=foo からドメイン名を取得したいとき

文字列からドメイン名を取得する場合

const url = 'https://example.com/piyo/?hoge=foo'
const domain = new URL(url).origin

console.log(domain) // https://example.com

表示中のページURLからドメイン名を取得する場合

console.log(location.origin) // https://example.com

ちなみに

const url = new URL('https://example.com/piyo/puni.js?hoo=foo')

console.log(url.host)     // "example.com"
console.log(url.hostname) // "example.com"
console.log(url.href)     // "https://example.com/piyo/puni.js?hoge=foo"
console.log(url.origin)   // "https://example.com"
console.log(url.pathname) // "/piyo/puni.js"
console.log(url.protocol) // "https:"
console.log(url.search)   // "?hoge=foo"

// もうパラメータを取得するためにこんなことしなくていいんだね🥺
const url = 'https://example.com/piyo/puni.js?hoge=hoo'
console.log(url.substring(url.indexOf('?'))) // "?hoge=foo"

となリます。

MDN: https://developer.mozilla.org/ja/docs/Web/API/URL/URL

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

福岡在住のフリーランスエンジニア
トライアスロンやボードゲームが好きです

【プログラミング】
バックエンド: PHP(主にLaravel)/Node.js
フロントエンド: React/Vue

【ボードゲーム】
オセロ: 全国大会出場(引退勢)
囲碁: 級位者大会で初段権利獲得
将棋: ウォーズ2級