I'm trying to create an analog for php's isset ($_GET[param])
but for JavaScript.
So long, I get this
[?&]param[&=]
But if param is at the end of URL (example.com?param) this regex won't work.
You can play with it here: https://regex101.com/r/fFeWPW/1
If you want to make sure your match ends with &
, =
or end of string, you may replace the [&=]
character class with a (?:[&=]|$)
alternation group that will match &
, =
or end of string (note that $
cannot be placed inside the character class as it would lose its special meaning there and will be treated as a $
symbol), or you may use a negative lookahead (?![^&=])
that fails the match if there is no &
or =
immediately after the current location, which might be a bit more efficient than an alternation group.
So, in your case, it will look like
[?&]param(?:[&=]|$)
or
[?&]param(?![^&=])
See a regex demo
JS demo:
var strs = ['http://example.com?param', 'http://example.com?param=123', 'http://example.com?param&another','http://example.com?params']; var rx = /[?&]param(?![^&=])/; for (var s of strs) { console.log(s, "=>", rx.test(s)) }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.