为@meouw +1 - 巧妙的解决方案!
另一种方法是使用 string.split。以下实现对于您正在搜索的参数及其值(即任何字符串)是灵活的。
function getUniqueParam (query, paramName) {
var i, row, result = {};
query = query.substring(1);
//split query into key=values
query = query.split('&');
for (i = 0; i < query.length; i++) {
row = query[i].split('=');
// if duplicate then set value to false;
if(result[row[0]]) {
result[row[0]] = false;
}
else {
result[row[0]] = row[1];
}
};
// return the requested param value
return result[paramName];
}
// Testing:
var a = '?LastName=abc&FirstName=xyz&insurance=2&insurance=3&insurance=4&insurance=5&BirthDate=01-01-2000';
var b = '?LastName=abc&FirstName=xyz&insurance=2&BirthDate=01-01-2000';
console.log(getUniqueParam(a, 'insurance'));
console.log(getUniqueParam(b, 'insurance'));