1

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

holden321
  • 1,166
  • 2
  • 17
  • 32
  • 1
    Replace `[&=]` with `(?:[&=]|$)` or `(?![^&=])` – Wiktor Stribiżew Nov 23 '17 at 11:06
  • This answer may help guide you: https://stackoverflow.com/a/901144/1612146 – George Nov 23 '17 at 11:07
  • Do you not just need to add on ? as in [?&]param[&=]? to make the [=&] optional? Then it matches http://example.com?param – mthomp Nov 23 '17 at 11:09
  • Why don't you just parse the entire query string into an object, then you can just check if a particular key is in the object. – Barmar Nov 23 '17 at 11:12
  • Why do people keep writing new parsers for standard data formats like URLs? And why do they insist on using regex for it? `console.log(new URL("http://example.com?param").searchParams.has("param"));` – Quentin Nov 23 '17 at 11:14
  • 1
    @Quentin https://developer.mozilla.org/en-US/docs/Web/API/URL/URL Maybe, because it not compatible with all browsers? – vaso123 Nov 23 '17 at 11:18
  • Wiktor Stribiżew, don't you want to add your answer? George, thanks. mthomp, no, because example.com?paramz would match. Barmar, long way, I look for a shorter :) Quentin, it should work in old browsers. – holden321 Nov 23 '17 at 11:18
  • Will this answer help too: https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript ? – Adriano Nov 23 '17 at 11:27

1 Answers1

3

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))
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Note that `[?&]param(?![^&=])` does not work inside a multiline test at regex101, but it works in real JS code when the strings are tested separately. – Wiktor Stribiżew Nov 23 '17 at 11:23