javascriptbookmarkletkirby

JS/bookmarklet to replace characters in the URL with some other characters, but retain domain name


When the bookmarklet is clicked, I need the URL, such as this:

https://example.com/test/page1/page2/page3/final page

To be replaced with:

https://example.com/panel/pages/test+page1+page2+page3+final-page

If it isn't clear, the domain remains the same, but then after it is /panel/pages/, followed by the same original page structure, but with + instead of /. Finally, if final page has a space (not all of them do), a - is used.

Not every URL I want this for has three pages before the final one. Some have just one or two. So, it would need to apply to all of them somehow.

The idea here is that the second link is used for editing the page, and the first is the live page. I want an easy way to open the page for editing. Ideally, the new URL would open in a new tab.

I'd love some direction, considering I'm a total newb at this.


Solution

  • How about this?

    (function(loc) {
      loc.href = `${loc.protocol}//${loc.host}/panel/pages/${
        loc
          .pathname
          .slice(1)
          .replace(/\//g, "+")
          .replace(/(\s|%20)/g, "-")
      }`;
    })(window.location)
    

    This creates a redirect to...

    1. protocol is http: or https:
    2. Adding // in between the domain and host
    3. The page host name
    4. We go to the hardcoded /panel/pages/
    5. loc.pathname gets everything including and after the / in the URL
    6. Because it includes the leading /, we must remove it so it does not become + as well with .slice(1)
    7. Then we replace all /s with +
    8. Replace all spaces (in the URL it's encoded as %20)

    Bookmarklet-ready code:

    javascript:(function(l){l.href=`${l.protocol}//${l.host}/panel/pages/${l.pathname.slice(1).replace(/\//g,"+").replace(/%20/g,"-")}`})(window.location)