-1

In a section of Sevelte tutorial, there's a piece of code like this:

view = pin ? pin.replace(/\d(?!$)/g, '•') : 'enter your pin';

I know \d means a digit, but can't figure out what (?!$) means.

(And because it's composed of all punctuation, I can't manage to google for an explanation.)

Please help, thanks.

Jyunhao Shih
  • 1,287
  • 2
  • 8
  • 9

2 Answers2

1

(?!$) Is a negative lookahead stipulation, where (?!) declares the negative lookahead and $ is what that the expression is "looking ahead" for (in this case, an end anchor).

A negative lookahead is an inverse of a positive lookahead, so it will be more intuitive to understand if you know what a positive lookahead is first: A digit followed by a positive lookahead \d(?=$) basically looks for anything that would be matched by \d$ but does not return the part inside the lookahead stipulation when returning a match. \d(?=$) will match any digit that is directly behind the end of the string. A negative lookahead will simply match every digit that is NOT directly behind the end of the string instead, ergo using \d(?!$) and replacing matches with a * basically turns every digit in the string into a * except for the last one.

For the sake of being thorough, you should know that (?<=) is a positive lookbehind that looks for matches in the characters immediately before the given token instead of after, and (?<!) is a negative lookbehind.

Regex101.com and RegExr.com are fantastic resources to use when you are learning regex, because you can insert a regular expression you don't understand and get a piece-by-piece explanation of an expression you don't understand and test strings in real time to experiment with what the expression captures and what it doesn't. Even if the built-in explanations don't make sense, you can still use them in situations like this to find out what something is called so you can search for it.

0
  • \d matches all digits
  • (?!something) means 'Negative Lookahead' for something
  • $ matches the end of a string

So when \d(?!$) is used, it matches all digits before the last character

In this string:

$$//www12.example@news.com<~>998123000dasas00--987

This will be matched (7 will not because it is the last character):

129981230000098

Referred to this answer and Regex Cheat Sheet

Julio
  • 5,208
  • 1
  • 13
  • 42
Muhid
  • 91
  • 5