I agree with both @netra.agarwal and @jacqueline-bosco — their ways would work just fine for sure. But hey, I’m here with a little present for you (another super cool method).
You can use ??
(Nullish Coalescing Operator) for a cleaner, modern approach.
If you’re using a modern version of JavaScript (ES2020+), this lets you handle null
or undefined
values specifically:
javascript
CopyEdit
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results?.[1] ?? 0;
}
Why this works:
- The
?.
(optional chaining) ensures you only accessresults[1]
ifresults
is notnull
orundefined
. - The
?? 0
part will return0
ifresults[1]
isnull
orundefined
, making it more explicit than the||
operator, which would also coerce other falsy values (likefalse
,0
, or''
) to0
.
That’s it — neat, clean, and modern! Adios!