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.
For your second example, it actually doesn’t return
null, it returns an empty string.Empty strings are falsy, they coerce to
falsein 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 returntrueonly if the match is falsy (an empty string):