天天看點

Useful code snippet to parse the key value pairs in URL

This issue is written based on review result of CECenter code.

下面這段代碼的目的是從A=a&B=b&C=c&D=d中解析出key A,B,C,D和value a,b,c,d:

Useful code snippet to parse the key value pairs in URL

雖然隻有4行,但是後面兩行每行至少包含substring和indexOf兩個字元串操作。

可以通過下面代碼裡的正規表達式高效地實作這個功能:

var test = "#token=Be&access_token=fff&id_token=ets&expires_in=3600&scope=full";
var anotherTry = function(value) {
var reg = /(?:^\#|&)(.*?)=(.*?)(?=&|$)/g;
var temp;
while((temp = reg.exec(value))!= null) {
console.log("Key: " + temp[1] + " value: " + temp[2]);
}
};
anotherTry(test);      
Useful code snippet to parse the key value pairs in URL

繼續閱讀