Why is the first test failing?
/^[ab](?=[cd])$/.test('ac') // => false
/^[ab](?=[cd])/.test('ac') // => true
Only the string 'ac', 'ad', 'bc' & 'bd' should pass.
No other strings like 'ac bd' or 'acbd'.
However, using the $
isn't helping in the 1st regex, whereas the 2nd one will also pass for strings like 'acbd'.
You need to understand how look-aheads work.
The (?=[cd])$
positive look-ahead checks if the following characters match the pattern that follows the look-ahead (in your case, the end of string). The end of string is not c
nor d
. Thus, there is no match.
You need to put the $
to the look-ahead to make it match a
:
^[ab](?=[cd]$)
See demo on Regex101.com
Debuggex Demo
This regex should pass:
/^[ab](?=[cd]$)/.test('ac')
Reason why
/^[ab](?=[cd])$/.test('ac')
is failing because $
(end of input) is not there after a
or b
(there is a letter c
after a
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With