Skip to content

Instantly share code, notes, and snippets.

@MauricioRobayo
Last active July 24, 2022 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MauricioRobayo/ce01b88676e67eb5dffb6770f0f9f57c to your computer and use it in GitHub Desktop.
Save MauricioRobayo/ce01b88676e67eb5dffb6770f0f9f57c to your computer and use it in GitHub Desktop.
Lookahead
The syntax is: X(?=Y), it means "look for X, but match only if followed by Y". There may be any pattern instead of X and Y.
For an integer number followed by %, the regexp will be \d+(?=%):
let str = "1 turkey has a discount of 30%";
alert(str.match(/\d+(?=%)/)); // 30, the number 1 is ignored, as it's not followed by %
Negative lookahead
Let’s say that we want a quantity instead, not a price from the same string. That’s a number \d+, NOT followed by $.
For that, a negative lookahead can be applied.
The syntax is: X(?!Y), it means "search X, but only if not followed by Y".
let str = "2 turkeys have a discount of 60%";
alert(str.match(/\d+\b(?!%)/g)); // 2 (the discount is ignored)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment