Search code examples
javascriptnode.jsurlurl-encodingurldecode

Change specific parameter of URL


I've node application and I'm getting the following URL (in req.header. of express)
I need to change the port number(of the redirect url) e.g. from 77777 to 88888,

I tried with parse encode and decode without success but maybe I miss something,

I need to use the standard (parse encode and decode) way and not just replace...(which works)

Any idea how to do that? I need at the end after I change this URL to keep it in exactly the same format (After encod/decode...) as follows.

http://gr-t6fa45e73.go.grp.corp:54001/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Fro-d3ma32e85.mo.grp.corp%3A77777%2Flogin%2Fcallback&client_id=zs6.node


Solution

  • How about using url

    var URL ="http://gr-t6fa45e73.go.grp.corp:54001/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Fro-d3ma32e85.mo.grp.corp%3A77777%2Flogin%2Fcallback&client_id=zs6.node";
    
    var parts = URL.split("redirect_uri="),    
    decoded = decodeURIComponent(parts[1])),
    red = url.parse(decoded);
    red.port=88888;
    URL = parts[0]+"redirect_uri="+encodeURIComponent(url.format(red));
    

    UPDATE Using this version of URI.js

    I use .build instead of .format.

    DEMO

    Result:

    http://gr-t6fa45e73.go.grp.corp:54001/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Fro-d3ma32e85.mo.grp.corp%3A88888%2Flogin%2Fcallback%26client_id%3Dzs6.node