Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redirect to another website (New ur has parameter) and add on current parameters (how to remove ? and add just &)

I’m passing URL parameters from the current link to another link but the new parameters are added as "&?firstName=test&lastName=testing" and should be just "&firstName=test&lastName=testing"

<script>
$('#redirectButton').click(function() {
  const url = window.location.href; 
  const params = url.split('/');  
  const parameter = params[params.length-1]; 
  
  const page2 = "www.newwebsite.com/page?existingParam=true" +parameter;
  window.location.href = page2
});
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If your URL is something like www.mywebsite.com/blah/blahblah/test?a=1&b=2, then the last item of the split list would be test?a=1&b=2. Blindly adding this to something like www.myotherwebsite.com/blah/test?existing=true would give www.myotherwebsite.com/blah/test?existing=truetest?a=1&b=2. However, you only want a=1&b=2 to be added (and of course, an & before all that). Thus, we can split by ? and add & plus the last part.

let url = 'www.mywebsite.com/blah/blahblah/test?a=1&b=2';
let redirectURL = 'www.myotherwebsite.com/blah/test?existing=true';
let splitL = url.split('/');

console.log('Redirecting to...');
console.log(redirectURL + '&' + splitL[splitL.length - 1].split('?')[1]);

This is assuming that your URL is not like www.someotherwebsite.com/test?a=1&text=Hello,%20how%20are%20you%20doing? with a question mark in the parameters. If it is, then you should use indexOf to find the index of the first question mark in splitL[splitL.length - 1], and use a slice from that index (plus 1) instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading