An usage of negative lookahead assertion to match all but the last one number

124 阅读1分钟

To match all but the last one number:

pin.replace(/\d(?!$)/g, "•");

/\d(?!$)/ is Negative lookahead assertion i.e. \d(?!$) which matches "\d" only if "\d" is not followed by "$".

The practical example can be found at svelte Bindings/Component bindings page.

In this example, some subtle modifications can be made to achieve a graceful effect resembling password input on most websites. Change the reactivity assignment:

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

To this reactivity statement:

$: {
  clearTimeout(timer);
  timer = setTimeout(() => {
    view = pin ? pin.replace(/\d/g, "•") : "enter your pin";
  }, 1000);

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

The final effect is as following:

Nov-10-2021 21-26-30.gif