Bounties /Pin to ProfileBookmark

2 Answer(s)

possible answer
@JaySODec 06, 2022 — You can use the window.location object, which contains information about the current URL. This object has several properties that you can use to access different parts of the URL, such as the protocol (e.g. "https:"), the hostname (e.g. "www.example.com"), the path (e.g. "/path/to/page"), the query string (e.g. "?key1=value1&key2=value2"), and the fragment identifier (e.g. "#top").

Here is an example of how you can use the window.location object to get each part of the URL into JavaScript variables:


const currentUrl = window.location;
const protocol = currentUrl.protocol; // e.g. "https:"
const host = currentUrl.host; // e.g. "www.example.com"
const pathname = currentUrl.pathname; // e.g. "/path/to/page"
const search = currentUrl.search; // e.g. "?key1=value1&key2=value2"
const hash = currentUrl.hash; // e.g. "#top"
possible answer
@mistamoleculJan 12, 2023 — When the URL isn't necessarily the current window.location, there is a modern way to parse URL strings. This is also useful when you're working with JavaScript outside the browser, such as Node -- you can import this standard module.


const myURL = 'https://google.com/?ham=true&number=10'
const parsedURL = new URL(myURL)

const protocol = parsedURL.protocol // 'https:'
const querystring = parsedURL.pathname // '?ham=true&number=10'


This is nifty because it allows you to leverage the URLSearchParams built-in to cleanly interact with querystring properties and values.


parsedURL.searchParams.has('ham') // true
parsedURL.searchParams.get('number') // '10'
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with Github
about: ({
version: 0.1.7 BETA 2.4,
whats_new: article editor v2,
up_next: tip code demos,
coming_soon: embeddable tipping,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh

version: 0.1.5,
notes: added pins + new badge

version: 0.1.4,
notes: home refresh + tools
)...
recent_tips: (
tipper: @JohnDavis,
amount: 250 SATS,
source: article

tipper: @Megan0910,
amount: 1000 SATS,
source: article

tipper: @JohnDavis,
amount: 250 SATS,
source: article
)...