I have a string like url params. I want to get insurance value if insurance param comes only one time in string.
For example:
1. Following string should produce result: false
?LastName=abc&FirstName=xyz&insurance=2&insurance=3&insurance=4&insurance=5&BirthDat开发者_StackOverflow社区e=01-01-2000
2. Following string should produce result: 2 (because only one insurance)
?LastName=abc&FirstName=xyz&insurance=2&BirthDate=01-01-2000
How can I do this in JavaScript / jQuery
I appreciate every answer. Thanks
Here's a function that will do what you want
function checkInsurance( queryString ) {
// a regular exression to find your result
var rxp = /insurance=(\d+)/gi
if( !queryString.match( rxp ) || queryString.match( rxp ).length !== 1 ) {
// if there are no matches or more than one match return false
return false;
}
// return the required number
return rxp.exec( queryString )[1];
}
+1 for @meouw - neat solution!
An alternative would be to use string.split. The following implementation is flexible about the param you are searching for and its value (i.e. any string).
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'));
精彩评论