Convert strings to boolean

Asked

Viewed 131 times

1

I’m dynamically adding one javascript and its src 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 the configuration argument of 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 observe the values as bad boolean I don’t know how to do this.

When adding 2 more replace() to replace booleans if the last argument is a boolean returns a string 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 solve this? If the last item of this "querystring" is a boolean actually returns a boolean?

1 answer

0

Maybe not the best solution, but you can know if it is a boolean value as follows:

var isTrue = (query.e == "true"); //compara com a string "true" e retorna true, caso sejam iguais
  • The object returned from querystring (if there is) will be merged with the object defaults at source... as these options are exclusively booleans and used extensively in the source I cannot check each input until because the "module" can be extended :(

Browser other questions tagged

You are not signed in. Login or sign up in order to post.