LoginSignup
0
2

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-08-06

https://example.com/piyo/?chu=peroこういう文字列からドメイン名を取得したいとき

これでいいのか?
よくなかった模様

function getDomainFromUrl(url) {
    const dummy = document.createElement('a')
    dummy.setAttribute('href', url)

    return dummy.protocol + '//' + dummy.hostname
}

const url = 'https://example.com/?chu=pero'
const domain = getDomainFromUrl(url)

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

追記

@il9437 さんからコメントでもっといい方法を教えていただきました!

メソッド作る必要なかった

const url = 'https://example.com/?chu=pero'
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?chu=pero')

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

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

となるようです
便利!!

0
2
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
0
2