Get URL parameter function that gets value of url part or returns true if it's there but with no val

Posted by LLer on Stack Overflow See other posts from Stack Overflow or by LLer
Published on 2010-06-16T15:37:40Z Indexed on 2010/06/16 16:02 UTC
Read the original article Hit count: 154

Filed under:
|

I'm using the following function to get a URL parameter.

function gup(name, url) {
  name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
  var results = new RegExp('[\\?&]'+name+'=?([^&#]*)').exec(url || window.location.href);
  return results == null ? null : results[1];
}

It works only if the parameter has a value, for example.

gup('a', 'http://example.com/page.php?a=1&b=2');

will return 1. But if I try

gup('a', 'http://example.com/page.php?a&b=2');

It returns null. I want it to return true because parameter "a" exists in that url, even though it has no value it's still there and gup() should return true. Could I get a bit of help rewriting this? I'm not that good with regex.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about regex