0

I have 2 variable with value and character '&' to determinate parameter (like URL parameter).

Note: This is not a parameter from URL and not is a Array!

variable1 = value1=bla&value2=ble&page=test&value4=blo&test=blu&car=red
variable2 = page=index&car=blue&other=yellow

I need compare 2 variables and eliminate duplicate parameters, and if have same parameter on variable1 and variable2, i need exclude parameter from variable1 and use parameter from variable2.

Like this:

value1=bla&value2=ble&page=index&value4=blo&test=blu&car=blue&other=yellow

How to get this?

4

1 Answer 1

2

I've build this JSFiddle to help you out. I've attempted to keep it as vanilla as possible and left comments.

Quickly – This simply parses the parameter string and replaces duplicate parameter names with the last value found. I couldn't tell exactly what you needed from your question; but maybe this will help get you going.

Here's the JSFiddle code for reference:

/**
 * Open up the console to see what's going on
 */

function parse(str) {
    // parse will split the string along the &
    // and loop over the result

    var keyValues, i, len, el, 
        parts, key, value, result;

    result    = {};
    sepToken  = '&';
    keyValues = str.split('&');

    i   = 0;
    len = keyValues.length;

    for(i; i<len; i++) {
        el    = keyValues[i];
        parts = el.split('=');
        key   = parts[0];
        value = parts[1];

        // this will replace any duplicate param 
        // with the last value found
        result[key] = value;
    }

    return result;
}

function serialize(data) {
    // serialize simply loops over the data and constructs a new string

    var prop, result, value;

    result = [];

    for(prop in data) {
        if (data.hasOwnProperty(prop)) {
            value = data[prop];

            // push each seriialized key value into an array
            result.push(prop + '=' + value);
        }
    }

    // return the resulting array joined on &
    return result.join("&");
}

function run() {
    // run this example

    var paramStr, data, result; 

    // paramStr has a duplicate param, value1
    paramStr = 'value1=bla&value1=foop&value2=ble&page=test&value4=blo&test=blu&car=red';
    data     = parse(paramStr);
    result   = serialize(data);

    return result;

}

console.log(run());
Sign up to request clarification or add additional context in comments.

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.