Convert strings to booleans

1

I'm dynamically adding a javascript and to its src I need to pass some parameters ... the following function creates this "querystring":

var querystring = {a:'b',b:true,c:'d',e:false};
var query = Object.keys(querystring).map((key) => {return [key, querystring[key]].map(encodeURIComponent).join("=");}).join("&");

// output: "a=b&b=true&c=d&e=false"

These values are used as configuration argument for javascript added ... To redeem these values for a object use the following function:

var scripts = document.body.getElementsByTagName('script'),
    query = false;

for (var i = 0; i < scripts.length; i++) {
     if ( (/module-name\/index.js/g.test(scripts[i].src)) ) {
         query = scripts[i].src.split('?')[1];
     }
}
if ( !!query ) {
    query = JSON.parse('{"' + decodeURI(query.replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}');
    console.log(query);

    // output: {a: "b", b: "true", c: "d", e: "false"}

The problem is that I just need to look at the values as booleans and I do not know how to do this.

Adding 2% more% to replace booleans if the last argument is a Boolean returns a% example:

// exemplo 1:
var query = "a=b&b=true&c=d&e=false";
query = JSON.parse('{"' + decodeURI(query.replace(/&/g, "\",\"").replace(/=/g,"\":\"")).replace(/"true"/g, true).replace(/"false"/g, false) + '"}');

console.log(query);

// output: {a:'b',b:true,c:'d',e:"false"};


// exemplo 2:
var query = "a=b&b=true&c=d&e=false&foo=bar";
query = JSON.parse('{"' + decodeURI(query.replace(/&/g, "\",\"").replace(/=/g,"\":\"")).replace(/"true"/g, true).replace(/"false"/g, false) + '"}');

console.log(query);

// output: {a:'b',b:true,c:'d',e:false,foo:'bar'};

How can I resolve this? If the last item of this "querystring" is a Boolean, does it actually return a Boolean?

    
asked by anonymous 10.04.2017 / 00:11

1 answer

0

It may not be the best solution, but you can tell if it is a Boolean value as follows:

var isTrue = (query.e == "true"); //compara com a string "true" e retorna true, caso sejam iguais
    
10.04.2017 / 19:28