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

asked Nov 23, 2017 at 11:05
8
  • 1
    Replace [&=] with (?:[&=]|$) or (?![^&=]) Commented Nov 23, 2017 at 11:06
  • This answer may help guide you: stackoverflow.com/a/901144/1612146 Commented Nov 23, 2017 at 11:07
  • Do you not just need to add on ? as in [?&]param[&=]? to make the [=&] optional? Then it matches example.com?param Commented Nov 23, 2017 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. Commented Nov 23, 2017 at 11:12
  • 1
    @Quentin developer.mozilla.org/en-US/docs/Web/API/URL/URL Maybe, because it not compatible with all browsers? Commented Nov 23, 2017 at 11:18

1 Answer 1

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))
}

answered Nov 23, 2017 at 11:21

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.