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 :
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.