Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

     

The URL Object

Here's a great trick to get URL properties from a string that I recently discovered thanks to dev.to userChris Bongers (Daily Dev Tips)

This method involves using theURL() constructor, available in all modern browsers.

consturl=newURL('http://www.example.com/snippet?utm_campaign=12345#documentation');
Enter fullscreen modeExit fullscreen mode

With the URL object, you can easily access URL properties as such:

{hash:"#documentation",host:"www.example.com",hostname:"www.example.com",href:"http://www.example.com/snippet?utm_campaign=12345",origin:"http://www.example.com",password:"",pathname:"/snippet",port:"",protocol:"http:",search:"?utm_campaign=12345",searchParams:URLSearchParams{},username:""}console.log(url.pathname);// Logs "/snippet"console.log(url.hostname);// Logs "www.example.com"
Enter fullscreen modeExit fullscreen mode

Note that one of the properties is thesearchParams object, which provides an interface to manipulate the URL's query string (we'll look at it in-depth in another article).

console.log(url.searchParams.get('utm_campaign'));// Logs "12345"
Enter fullscreen modeExit fullscreen mode

Before this awesome constructor came along, it was common to achieve the same result by creating an anchor tag in order to use the DOM's built-in methods to retrieve the URL info:

consta=document.createElement('a');a.href='http://www.example.com/snippet?utm_campaign=12345#documentation';a.pathname// "/snippet"a.hostname// "www.example.com"a.search// "?utm_campaign=12345"
Enter fullscreen modeExit fullscreen mode

While this worked, it felt cumbersome to have to create a document element solely to retrive URL data and could potentially confuse readers of your code of what your intent was. Plus, this would only work with the Web API and not in other environments like Node whereURL() would clearly be the superior method. 👑

Links

MDN Article on URL() Interface


Check out more #JSBits at my blog,jsbits-yo.com. Or follow me onTwitter!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
mohsenalyafei profile image
Mohsen Alyafei
  • Location
    Qatar
  • Joined

Nice one. Thanks

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

3rd Party JS Developer, Blogger, and Competitive Olive Eater
  • Location
    Austin, TX
  • Joined

More fromJS Bits Bill

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp