1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

1
Last updated at Posted at 2020-08-06

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

1
4
2

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?