Last active
July 24, 2022 01:35
-
-
Save MauricioRobayo/ce01b88676e67eb5dffb6770f0f9f57c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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+(?=%): |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 % |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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". |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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