我已經建立了這個JSFiddle來幫助你。我試圖保持它作爲香草,並留下評論。
迅速 - 這只是解析參數字符串並替換重複的參數名與上次值發現。我無法確切地告訴你你的問題需要什麼;但也許這會幫助你走。
這裏是代碼的jsfiddle供參考:
/**
* 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());
轉換的字符串對象,將它們合併,並將結果轉換回一個字符串。 –
你可以舉個例子嗎? – rafaelfndev
轉換:http://stackoverflow.com/a/7128954/218196,合併:http://stackoverflow.com/q/171251/218196,序列化:http://stackoverflow.com/q/1714786/218196 –