SO - Param String Parsing Answer

http://stackoverflow.com/questions/24459671/jquery-how-to-remove-duplicate-parameter-on-string-not-array

by Aubrey Taylor

JavaScript

/**
 * 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());