Generate URLs with parameters on the knee and best practice

Once, I saw code in a project of a neighboring team that generated a string with URL parameters for subsequent insertion into an iframesrc attribute.


This article may seem superfluous, obvious or too simple, but since this is found in wildlife, you should not be silent about this, but rather, share best-practices.


So here it is, the original code:


const createQueryString = (param1, param2, objectId, timestamp, name) => {
  const encodedTimestamp = encodeURIComponent(timestamp);
  const delimiter = '&';
  const queryString = `${param1}${delimiter}
        param2=${param2}${delimiter}
        objectId=${objectId}${delimiter}
        itemTimestamp=${encodedTimestamp}${delimiter}
        itemName=${name}`;
  return queryString.replace(/ /g, '%20');
};

For reference, param1and param2in the original code have speaking names. And their values ​​can be any strings with lots of invalid characters for URL characters


What problems does this code have?


  • -, encodeURIComponent , . ( , );
  • -, , - template string `; .replace(), ;
  • -, - , .

?


:


const delimiter = '&'; //      
const createQueryString = (param1, param2, objectId, timestamp, name) => {
  const queryString = [
    `param1=${encodeURIComponent(param1)}`,
    `param2=${encodeURIComponent(param2)}`,
    `objectId=${encodeURIComponent(objectId)}`,
    `itemTimestamp=${encodeURIComponent(timestamp)}`,
    `itemName=${encodeURIComponent(name)}`
  ].join(delimeter);
  return queryString;
};

? . , encodeURIComponent. , . .


? ! :


const createQueryString = (param1, param2, objectId, timestamp, name) => {
  const queryParams = {
     param1,
     param2,
     objectId,
     itemTimestamp: timestamp,
     itemName: name
  };
  const encodeAndJoinPair = pair => pair.map(encodeURIComponent).join('=');
  return Object.entries(queryParams).map(encodeAndJoinPair).join('&');
};

. , β€” .


, . , .



. , ? , queryParams. . , . , :


const encodeAndJoinPair = pair => pair
  .map(encodeURIComponent)
  .join('=');

const createQueryString = objectParams => Object
  .entries(objectParams)
  .map(encodeAndJoinPair)
  .join('&');
};

utils.js .


URLSearchParams


Web API. URLSearchParams .


:


const createQueryString = objectParams => new URLSearchParams(objectParams).toString();

Internet Explorer, , , https://www.npmjs.com/package/url-search-params-polyfill .



If the code seems verbose, confusing, then there are probably simple ways to improve it.
And there is also the possibility that the functionality you need is implemented at the Web API level.


All Articles