Home > Back-end >  How to keep a URL get from the current address un-encoded in JavaScript?
How to keep a URL get from the current address un-encoded in JavaScript?

Time:08-29

I have a JavaScript that replaces part of the href of links with the current URL (window.location.href). But I find that the URL replaced is encoded, meaning it is not exactly the same as the original URL.

Desired result: ?redirect=www.example.com/path/slug
Not desired: ?redirect=www.example.com%2path%2slug

I tried to use something like decodeURI near the end of the script but failed.

Here is the working script:
( Also trying on CodePen: [https://codepen.io/pen/MWVMmZW][1] )

$(function () {
  $("a[href*='redirect']").each(function () {
    const url_str = $(this).attr("href");
    const this_url = new URL(url_str);
    if (this_url.searchParams.get("redirect")) {
      // Get the current url from the browser
      // Remove protocol
      const current_url = window.location.href.split("://")[1];
      // Remove the last slash
      let regex = /\/$/;
      let clean_url = current_url.replace(regex, "");
      const redirect = this_url.searchParams.set("redirect", clean_url);
      $(this).attr("href", this_url.href);
    }
  });
});
body {
  padding: 10px 20px;
}
a {
  display: block;
  margin: 0 0 5px 0;
  text-decoration: none;
}
hr {
  height: 0px;
  margin: 30px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Objective:<br>To change whatever text after <strong>?redirect=</strong> in the links to the current visiting URL using JavaScript. ( only after <strong>?redirect=</strong> )</p>
<a href="https://app.example.com/?redirect=www.111.com">Link A</a>
<a href="https://app.example.com/?redirect=www.222.com">Link B</a>
<a href="https://app.example.com/?redirect=www.333.com">Link C</a>
<p>So, if the current address is https://www.example.com/about/dog<br>The above links should change to:<br>→ https://app.example.com/?redirect=www.example.com/about/dog</p>

<hr />

<p>Other URLs remain unchanged on the web page.</p>
<a href="https://www.example.com">Other Link 01</a>
<a href="https://www.example.com/about">Other Link 02</a>
<a href="https://app.example.com/?search=game">Other Link 03</a>

CodePudding user response:

The correct answer is to alter the final part like it follows:

      const redirect = this_url.searchParams.set("redirect", clean_url);
      $(this).attr("href", decodeURIComponent(this_url.href));

Please delete the accepted sign.

  • Related