views:

30

answers:

1

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.

A: 

For your second example, it actually doesn't return null, it returns an empty string.

Empty strings are falsy, they coerce to false in boolean context, so you could use this in the second branch of the ternary.

There you know that something was matched (in results[1]), and you can return true only if the match is falsy (an empty string):

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

gup('a', 'http://example.com/page.php?a&b=2');   // true
gup('a', 'http://example.com/page.php?a=1&b=2'); // "1"
gup('a', 'http://example.com/page.php?b=2');     // null
CMS
Thank you. Didn't realize it was so simple.
this is a dead end