2

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&BirthDate=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

4
  • 1
    you looking for this?
    – indiPy
    Commented Mar 5, 2011 at 10:38
  • @alliswell: Thanks. I used the top answer's function of question that you mentioned. It returns first insurance value without condsidering no. of insurance in string. I want to return insurance value only when there is only one insurance in the string. So now I have to add a check for the no of insurance in string.
    – Awan
    Commented Mar 5, 2011 at 10:53
  • you are welcome, and use regex as it mentioned or simple conditional check will work.
    – indiPy
    Commented Mar 5, 2011 at 11:00
  • See also the Query String Object plugin.
    – outis
    Commented Mar 5, 2011 at 11:46

2 Answers 2

4

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];
}
0
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'));
1
  • There is a discussion on regex vs. string.split performance here
    – johnhunter
    Commented Mar 5, 2011 at 11:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.