简体   繁体   中英

How to replace part of the a link to the current URL by JavaScript or with jQuery?

I've got a link that exists on many pages, which I would like to use JavaScript to make the later part of the link to be changed according to the current url * of the visiting page.

(* current url mentioned here = the current web address appears on the browser's address bar)

What is the right way to change URL after ?redirect= to the current visiting URL using JavaScript?

For example, this is the original:

<a href="https://app.example.com/?redirect=www.example.com">Link</a>

Now, the current url is https://www.example.com/game?q=123 , the desired result would be:

<a href="https://app.example.com/?redirect=https://www.example.com/game?q=123">Link</a>

Thanks a lot

Trying to learn from these posts, but was not successful yet...
how to replace part of the URL with JavaScript?
Get the current URL with JavaScript?
Replace a part of the current URL

What I would do is get the href attribute from all anchor links. Create a new URL() object so you can work the url parameters. Replace the value and finally replace the href attribute with the result.

For example (explanation in comments):

 // Make sure the document is loaded before you start working with it document.addEventListener("DOMContentLoaded", function(e){ // Get all anchor links present in the document and loop through them document.querySelectorAll("a").forEach(function(element){ // Get the value of the href attribute const url_str = element.getAttribute("href"); // Create a new URL object so we can work with it const url = new URL(url_str); // Check if the anchor tag should be affected or not if(url.searchParams.get('redirect')) { // Get the current url from the browser const current_url = window.location.href; // Set the redirect parameter to the value of current_url const redirect = url.searchParams.set("redirect", current_url); // Replace the href attribute with the new url element.setAttribute("href", url.href); // This is just to show it working. You can remove this. console.log(element.getAttribute("href")); } }); });
 <a href="https://app.example.com/?redirect=www.example.com">Link</a> <a href="https://app.example.com/?redirect=www.different.com">Link</a> <a href="https://app.example.com/">Link</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM