2

I'm working on the datalayer of a website and I am required to pass a string filled in with values from the site's backend.

Here is the structure of the variable I need to pass:

> Before encoding:

transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_va lue=25.20;item_quantity=1; transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_va lue=25.20;item_quantity=1;

> After encoding:

transaction_id%3D0815%2F2009%3Btransaction_cid%3D54AB%3Bitem_id%3D40216304 5080%3Bitem_value%3D25.20%3Bitem_quantity%3D1%3Bitem_id%3D847163029054%3Bi tem_value%3D16.81%3Bitem_quantity%3D2

I have managed to create an array with the necessary data in this form:

'[{"transaction_id":"233684","transaction_cid":"d2871c13c507583048d8ecf4a16f94c0","i tem_id":"3524","item_value":"4915.13","item_quantity":"1"}]',

But what I need is all these elements of the array in a url encoded string.

I am out of ideas since all that I try seems to not work.

Using JSON.stringify keeps the ":" and the """, using alert() or join also keeps the ":" and is not performant.

EDIT:

Example array:

arr : {key1: 'a', key2:'b', key3:'c'}

non encoded result:

str : 'key1=a;key2=b;key3=c'

desired result:

str : 'key1%3Da%3Bkey2%3Db%3Bkey3%3Dc'

1
  • Show how you create the array, would be simpler to fix it there Commented Jun 28, 2016 at 16:29

3 Answers 3

3

Replace JSON.stringify with encodeURIComponent:

So, in the example above you have an array with one object. To parse that, I would do:

var params = elementArray[0];
var encoded_params = [];
for (var prop in params){
    if (params.hasOwnProperty(prop)) {            
        encoded_params.push(prop+ "=" +encodeURIComponent(params[prop]));
    }
}
var query_string = "?" + encoded_params.join("&");

NOTE: I would prefer to solve this from the beginning, w/ the original string you have:

transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_va lue=25.20;item_quantity=1;

// break string into components by splitting on `;`:
var data_as_str = "transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_va lue=25.20;item_quantity=1;";
var raw_params = data_as_str.split(";");

// create a new array where we will store our encoded params
var encoded_params = [];

// traverse the split string components
for (var i=0; i<raw_params.length; i++){
    var element = raw_params[i];

     // check that the element exists 
     // for example, the trailing `;` will create an empty element
     // which we do not want to include
    if (!element){
        continue;
    }

    // split on `=` to get key, value
    var key = element.split("=")[0];
    var value = encodeURIComponent(element.split("=")[1]);

    // build a new param string and push to clean array
    encoded_params.push(key+ "=" +value);
}

// after loop has completed, join elements 
// in clean array to complete query string
var query_string = "?" + encoded_params.join("&");
alert(query_string);
Sign up to request clarification or add additional context in comments.

7 Comments

Hey Jordan thanks for the answer but i specified it doesnt work
This won't create query params
hmm - maybe i'm misunderstanding the question. after encoding the urls, do you need to combine them into a query string?
Clearly says : "I need is all these elements of the array in a url encoded string"
Updated to build the query_string
|
0

Inspired from Jose's answer:

const arr = {key1: 'a', key2:'b', key3:'c'}
encodeURIComponent(Object.entries(arr).map(([k,v]) => `${k}=${v}`).join('&'))

Comments

-1

If you're using jQuery you can use $.param() . If you don't, you can loop over the keys of Object and format your QueryString. In the example I use Object.keys() to get the array of keys, Array.map() to loop over the keys and return a new Array, the ES6 template String. With encodeURIComponent you get t he encoded QueryString.

var obj = {key1: 'a', key2:'b', key3:'c'};

console.log(encodeURIComponent($.param(obj)));

console.log(encodeURIComponent(Object.keys(obj).map(key=>`${key}=${obj[key]}`).join('&')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As pointed in the other answer, you can do this from the first String:

var str = "transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_va lue=25.20;item_quantity=1;transaction_id=0815/2009;transaction_cid=54AB;item_id=402163045080;item_value=25.20;item_quantity=1;";

console.log(encodeURIComponent(str.split(';').filter(a=>a).join('&')));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.