js string to query string code example
Example 1: javascript convert object to querystring
const queryString = new URLSearchParams(props.location.search);
var queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
for (let param of queryString.entries()) {
console.log(param);
}
Example 2: get query string javascript nodejs
const querystring = require('querystring');
const url = "http://example.com/index.html?code=string&key=12&id=false";
const qs = "code=string&key=12&id=false";
console.log(querystring.parse(qs));
console.log(querystring.parse(url));
Example 3: string to query string javascript
serialize = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
console.log(serialize({
foo: "hi there",
bar: "100%"
}));
Example 4: javascript object to query string
queryBuilder = function(obj, prefix) {
var str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(
serialize({
foo: "hi there",
bar: {
blah: 123,
quux: [1, 2, 3]
}
})
);