SOLVED

Javascript help - Is this possible?

Go to solution
SanfordWhiteman
Level 10 - Community Moderator

Re: Javascript help - Is this possible?

This part of the code is a pattern you'll see in a lot of my code snippets... or perhaps a better term than "pattern" in this case would be "schtick." 🙂

 

The schtick relies on the fact that all browsers have a built-in URL parser & builder. It's not a query string parser, so it doesn't break down the implicit names and values within the query string.* But for accurately breaking out the standard parts of a URL — protocol, hostname, pathname, querystring/search, hash/fragment — it should always be used instead of attempting to roll your own. You would be surprised at how often people mess up something so simple as parsing a URL on its known separators, b/c they don't take the URI standard (RFC 3986) into account.

 

Anyway, to take advantage of that URL parser, you need what's called a "Location" object. To make one of those, you can create an A element and then set its href to the full URL. Then all the standard parts are parsed flawlessly by the browser and can be replaced one-by-one.

 

 

 

* Late-model browsers have URLSearchParams, but it's not fully implemented in IE,

so you must use a custom polyfill for this function if you want it work in full on the 2020 web.