How do I pass a URL with multiple parameters into a URL?

前端 未结 6 1781
甜味超标
甜味超标 2020-12-08 13:33

Basically I\'m trying to pass a URL like this:

www.foobar.com/?first=1&second=12&third=5

into a URL like this:

http         


        
6条回答
  •  被撕碎了的回忆
    2020-12-08 13:36

    I see you're having issues with the social share links. I had a similar issue at some point and found this question, but I don't see a complete answer for it. I hope my javascript resolution from below will help:

    I had default sharing links that needed to be modified so that the URL that's being shared will have additional UTM parameters concatenated.

    My example will be for the Facebook social share link, but it works for all the possible social sharing network links:

    The URL that needed to be shared was:

    https://mywebsitesite.com/blog/post-name
    

    The default sharing link looked like:

    $facebook_default = "https://www.facebook.com/sharer.php?u=https%3A%2F%2mywebsitesite.com%2Fblog%2Fpost-name%2F&t=hello"
    

    I first DECODED it:

    console.log( decodeURIComponent($facebook_default) );
    =>
    https://www.facebook.com/sharer.php?u=https://mywebsitesite.com/blog/post-name/&t=hello
    

    Then I replaced the URL with the encoded new URL (with the UTM parameters concatenated):

    console.log( decodeURIComponent($facebook_default).replace( window.location.href, encodeURIComponent(window.location.href+'?utm_medium=social&utm_source=facebook')) );
    
    =>
    
    https://www.facebook.com/sharer.php?u=https%3A%2F%mywebsitesite.com%2Fblog%2Fpost-name%2F%3Futm_medium%3Dsocial%26utm_source%3Dfacebook&t=2018
    

    That's it!

    Complete solution:

    $facebook_default = $('a.facebook_default_link').attr('href');

    $('a.facebook_default_link').attr( 'href', decodeURIComponent($facebook_default).replace( window.location.href, encodeURIComponent(window.location.href+'?utm_medium=social&utm_source=facebook')) );

提交回复
热议问题