Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - How to auto insert/add colon (:) after every 2 character in angular

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...