3

I want to auto insert a colon (:) after every 2 character in my input:

HTML

<input nz-input type="text" appLimitInput="textAndNumbers" name="mac" 
  formControlName="mac" (keydown.space)="$event.preventDefault();"
  onDrag="return false;" onDrop="return false;" onPaste="return false;">

Desired affect:

When I try to input AB then it will automatically add colon then when I type another text which is CD

then It will be like this AB:CD then when I try to delete/erase the CD then It will auto delete/erase the colon.

AB:CD:EF:GH:IJ:KL

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
  • Does this answer your question? [Automatically inserting "-" or "/" character for MM-YYYY textfields?](https://stackoverflow.com/questions/41858073/automatically-inserting-or-character-for-mm-yyyy-textfields) – pilchard Jan 12 '21 at 10:46

1 Answers1

6

You can add an input event to your input element that triggers a component method that will reformat it's value as follows:

Template:

<input (input)="reformat($event) />

Component:

reformat(event) {
  if (event.data) { // We don't want it to trigger on delete so we make sure there is data in the event (the entered char)
    const two_chars_no_colons_regex = /([^:]{2}(?!:))/g;
    event.target.value = event.target.value.replace(two_chars_no_colons_regex, "$1:");
  }
}

Regex explanation:
/../g Javascript regex literal syntax with global flag which matches all occurrences of the regex
() - A selection group we will reference later as $1
[^:] - Every char except colons
{2} - Preceding expression should come twice
(?!:) - Preceding expressions should not have colons after it \

Here is a working StackBlitz

Amit Hadary
  • 498
  • 1
  • 3
  • 11