var keys = {};
source.replace(
/([^=&]+)=([^&]*)/g,
function(full, key, value) {
keys[key] =
(keys[key] ? keys[key] + "," : "") + value;
return "";
}
);
var result = [];
for (var key in keys) {
result.push(key + "=" + keys[key]);
}
return result.join("&");
}
alert(compress("foo=1&foo=2&blah=a&blah=b&foo=3"));
我仍然混淆这个/([^ =&] +)=([^&] *)/ g,+和*用于?
答案 0 :(得分:1)
^表示不是这些,+表示一个或多个匹配的字符,()表示组。 *是任何匹配的数量(0 +)。
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
因此,通过观察它,我猜它取代了任何不是=& =&或& =&或==,这很奇怪。
答案 1 :(得分:0)
+
和*
被称为量词。它们确定子集匹配的次数(紧接在它们之前的字符集通常与量词所适用的[]
或()
重叠)重复。
/ start of regex
( group 1 starts
[^ anything that does not match
=& equals or ampersand
]+ one or more of above
) group 1 ends
= followed by equals sign followed by
( group 2 starts
[^ anything that does not match
=& ampersand
]* zero or more of above
) group 2 ends
/ end of regex