How to parse url parameters using queryString or any other method

My question is simple. I know that the npm query string does the job, but has a special case. My query parameters are as follows:

params={

foo:'bar',
data:[1,2,3],
data2:[4,5,6]
} 

I need to output something like ?foo=bar&data=1,2,3&data2=4,5,6

not what query-sting has done . query-sting prints it as

?foo=bar&data=1 &data=2&data=3..........

+4
source share
4 answers

The problem you are facing can be solved as follows:

const queryString = require('query-string')

const seacrh=queryString.stringify(params)

the above line expresses search=?foo=bar&data=1%0C2%0C3&data2=4%0C5%0C6

To remove an illogical character, simply decrypt the URL using the lines of code below

const search1=decodeURIComponent(seacrh);

DecodeURIComponent decodes these illogical strings.

+2
source

, .

array.join, = .

var params={
  foo:'bar',
  data:[1,2,3],
  data2:[4,5,6]
};

//?foo=bar&data=1,2,3 & data2=4,5,6

console.log(
  `?foo=${params.foo}&data=${params.data.join(',')}&data2=${params.data2.join(',')}`);
Hide result
0

, :

var params = {
  foo:   'bar',
  data:  [1,2,3],
  data2: [4,5,6]
};

function toQuery (params) {
  var queryString = '';
  // Check that we've been suplied with an object.
  if (params.constructor !== Object) {
    return queryString;
  }
  // Iterate over parameters
  for (var param in params) {
    if (!params.hasOwnProperty(param)) {
      continue;
    }
    if (typeof params[param] === 'string' || typeof params[param] === 'number') {
      queryString += '&' + param + '=' + params[param];
    }
    if (params[param].constructor === Array && params[param].length) {
      queryString += '&' + param + '=' + params[param].join(',');
    }
  }
  // Change first '&' to '?'
  if (queryString.length) {
    queryString = '?' + queryString.substring(1);
  }
  // Return the query string, empty string if no usable parameters.
  return queryString;
}

console.log(toQuery(params));
Hide result
0

:

let params = {
  foo: 'bar',
  data: [1, 2, 3],
  data2: [4, 5, 6]
};

let queryString = Object.keys(params).map(
  key => `${key}=${params[key]}`
).join('&');

console.log(queryString)
Hide result
  • the string constructor will automatically separate the array with commas
  • it is very elementary and does not include URI encoding, etc.
0
source

Source: https://habr.com/ru/post/1684820/


All Articles