
URLオブジェクトへの変換忘れついて
突然ですが問題です。
以下のJavaScriptのコードはどのような結果になるでしょうか。
const url = 'https://iwb.jp/#sample'
const result1 = url.hash
const result2 = url.host
console.log(result1)
console.log(result2)
正解はどちらもundefinedになります。
JavaScriptでhashやhostなどのURLのプロパティは文字列には使えません。
そのためnew URL()を使ってURLオブジェクトに変換する必要があります。
const url = new URL('https://iwb.jp/#sample')
const result1 = url.hash
const result2 = url.host
console.log(result1) // #sample
console.log(result2) // iwb.jp
JavaScriptを学習する上でlocation.hrefについては必ず学ぶことになるのですが、new URL()については初心者向けのJavaScriptの参考書には書かれていないことがあり、学習していないケースがあるようです。