0

I want to achieve something like this. If I give input as like this before

const partofurls = {
  protocol: 'https',
  host: 'hosturl',
  port: 8080,
  endpoint: 'someendpoint',
  queryparams: {
    key1:value1,
    key2:value2
  }
}

I want to get the URL as below

https://hosturl:8080/endpoint?key1=value1&key2=value2

In javascript or reactjs is there any way to achieve this?

I am getting these fields from the user. If the user added slash '/' at the end of the hosturl and if they have added the '/' at the beginning of endpoint also, then I will end up having two slashes in between hosturl and endpoint. Like this there are many other cases.

To resolve all these problems, is there any standard module or library available in reactjs or javascript?

3 Answers 3

1

You can build something like this

const urlObj = {
  protocol: 'https',
  host: 'hosturl',
  port: 8080,
  endpoint: 'someendpoint',
  queryparams: {
    key1: 'value1',
    key2: 'value2'
  }
}

let { protocol, host, port, endpoint, queryparams } = urlObj
let encodeQuery = new URLSearchParams(queryparams).toString()

let url = `${protocol}://${host}:${port}/${endpoint}?${encodeQuery}`

console.log(url)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. In my case, port and queryparams are optional. If they exists they should be appended otherwise they should be omitted from the output URL. Also, basically I am getting these fields from the user. If they have added slash '/' at the end of the host and if they have added the '/' at the beginning also, then I will end up having two slashes in between hosturl and endpoint. So I wanted to know is there any standard module or library available in reactjs or javascript respectively.
@siddiq this is just an example, you can simply add if else condition to handle values are present or not, there this is one such module which does the same this build-url
0

In Javascript, you can try following:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

and get all parameters:

function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}

And then in the react, you can use the react router

<Route 
 path="{url}"
 component={UserComponent} />

For example, userid is the url paramenter

class UserComponent extends React.Component{
 render(){
  let userId = this.props.match.params.userId;
  // rest of the code
 }

Here is how we use it:

import queryString from 'query-string';

class UserComponent extends React.Component{
 render(){
  // url is 'https://www.example.com/user?id=123&type=4';
  let url = this.props.location.search;
  let params = queryString.parse(url);
  console.log(params);
  // The result will be like below
  // { id: 123, type: 4 }
  // other code
 }
}

Comments

0

Try creating an URL object.

const u = new URL("http://www.test.com"); //dummy url
u.protocol = "https:";
u.hostname = "hosturl";
u.pathname = "/endpoint";
u.port = "8080"

searchParams = new URLSearchParams();
searchParams.append("key1", "value1");
searchParams.append("key2", "value2");

console.log(`${u}?${searchParams.toString()}`);
// https://hosturl:8080/endpoint?key1=value1&key2=value2

For more information, https://developer.mozilla.org/en-US/docs/Web/API/URL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.