1

I have a URL that includes a product ID which can be in the following format:

One alphabetical letter followed by a number of any number of digits, then an underscore, and then any number of digits and underscores.

So this is a valid product id: c23_02398105 and so is this: c23_02398105_9238714.

Of course in a URL, it's sandwiched between other query string items, so in this url, i want to extract just the id:

http://www.mydomain.com/product.php?action=edit&id=c23_02398105&side=1

I've been trying a regex something along the lines of this, to no avail:

/&id=[a-z]_[(0-9)*]&/

What's the correct way to extract the product id?

user961627
  • 12,379
  • 42
  • 136
  • 210
  • 2
    http://stackoverflow.com/questions/647259/javascript-query-string http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values – Andreas Feb 02 '13 at 15:22
  • @Andreas: i would have pin-pointed the answer too as i think the accepted answer could be made better (the second link you provided). http://stackoverflow.com/a/5158301/17447 – naveen Feb 02 '13 at 16:29
  • 1
    @user961627: http protocol is pretty specific, regex is generally inefficient. With web applications becoming more and more script-intensive, you don't want maximize optimization where you can. Some would call this over or microoptimization, but when you're still supporting IE7/IE8 you would understand that it is needed. – vol7ron Feb 02 '13 at 16:57
  • I'll also add that my answer is a modified one from the link @Andreas posted (I should update it there), which is probably overkill, but more robust for your needs. – vol7ron Feb 02 '13 at 18:55

4 Answers4

1
function qry(sr) {
  var qa = [];
  for (var prs of sr.split('&')) {
    var pra = prs.split('=');
    qa[pra[0]] = pra[1];
  }
  return qa;
}

var z = qry('http://example.com/product.php?action=edit&id=c23_02398105&side=1');
z.id; // c23_02398105

Source

Zombo
  • 1
  • 62
  • 391
  • 407
  • May be short enough to get what you want, but will not handle multiple IDs eg `http://www.mydomain.com/product.php?action=edit&id=c23_02398105&id=c24_40340343403&id=c23_23423423_23423423` see my answer below – vol7ron Feb 02 '13 at 16:13
1

The below returns an array of values for each key, so if you wanted to get a string for the below, join the values with some delimiter (eg params.id.join(',')) to get your comma-delimited string of IDs.

See Fiddle


http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash

Handles:

  • Regular key/value pair (?param=value)
  • Keys w/o value (?param : no equal sign or value)
  • Keys w/ empty value (?param= : equal sign, but no value to right of equal sign)
  • Repeated Keys (?param=1&param=2)
  • Removes Empty Keys (?&& : no key or value)

Code:

  • function URLParameters(_querystring){
        var queryString = _querystring || window.location.search || '';
        var keyValPairs = [];
        var params      = {};
    
        queryString = queryString.replace(/^[^?]*\?/,''); // only get search path
    
        if (queryString.length)
        {
           keyValPairs = queryString.split('&');
           for (pairNum in keyValPairs)
           {
              if (! (!isNaN(parseFloat(pairNum)) && isFinite(pairNum)) ) continue;
              var key = keyValPairs[pairNum].split('=')[0];
              if (!key.length) continue;
              if (typeof params[key] === 'undefined')
                 params[key] = [];
              params[key].push(keyValPairs[pairNum].split('=')[1]);
           }
        }
        return params;
    }
    

How to Call:

  • var params = URLParameters(<url>); // if url is left blank uses the current page URL
    params.key;                    // returns an array of values (1..n) for the key (called 'key' here)
    

Example Output for Given Keys ('key','keyemptyvalue','keynovalue') using Above URL:

  • key            ["value"]
    keyemptyvalue  [""]
    keynovalue     [undefined, "nowhasvalue"]
    
vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • i did not downvote, but have you seen this by James Padolsey? http://james.padolsey.com/javascript/bujs-1-getparameterbyname/ – naveen Feb 02 '13 at 16:35
  • @naveen I think some time ago - it's nice, but the issue is that (1) regex isn't so efficient, (2) If you want more than one param, his method isn't efficient, (3) There may be a time where you don't know the param name, his code you have to supply the key, rather than getting a list of all results, (4) There are times where you want to pass actions as just keys (without values), so the code above handles this, but his will only return values for the key, so a url like `www.abc.com?doSomething`, mine will show `doSomething` exists, but has an `undefined` value – vol7ron Feb 02 '13 at 16:48
  • His will also show `undefined`, but that's regardless if you try to call 'doSomething' or 'doesntReallyMatter' - so regardless of what you're trying to retrieve, his will ***always*** show `undefined` if it has no value – vol7ron Feb 02 '13 at 16:51
  • Finally, I've been moving towards a Cocoa naming convention; where getters don't use `get` as part of the function or method names. So instead of `getParametersByName`, they'd recommend `parametersByName` - causing me to update my function name too :) – vol7ron Feb 02 '13 at 16:53
1

You can use JavaScript string functions instead of regexp like this:

var url = "http://www.example.com/product.php?action=edit&id=c23_02398105&side=1";
var idToEnd = url.substring(url.search("&id")+4, url.length);
var idPure = idToEnd.substring(0, idToEnd.search("&"));
alert(idPure);

the output is c23_02398105

Eyad Farra
  • 4,403
  • 1
  • 24
  • 26
  • That sounds awfully painful. Why not just explode the string on the ?, &, and = to get each key value pair in a nice array?! – rodrigo-silveira Feb 02 '13 at 16:58
  • 1
    @svnpenn was probably best for your needs. The problem with this answer is that if you have something like `action=squid&id=...`, it'll match the `id` from the squid (what you don't want) and return `id=c23_`. @rodrigo-silveira has a better point. – vol7ron Feb 02 '13 at 18:59
0

The following expression fits your description

/&id=([a-z]\d*_[\d_]*)/

It assumes that the letter is lower-case, and that there is only one id in the url in the specified format, or that the one you want is the first one.

var url =
   'http://www.mydomain.com/product.php?action=edit&id=c23_02398105&side=1';

var m = url.match( /&id=([a-z]\d*_[\d_]*)/ );

console.log( m && m[1] );    // 'c23_02398105'
MikeM
  • 13,156
  • 2
  • 34
  • 47