[英]How to auto insert/add colon (:) after every 2 character in angular
我想在輸入的每 2 個字符后自動插入一個冒號( :
):
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;">
期望的影響:
當我嘗試輸入AB
時,它會自動添加冒號,然后當我輸入另一個文本CD
時
然后它會像這樣AB:CD
然后當我嘗試刪除/擦除CD
時它會自動刪除/擦除冒號。
AB:CD:EF:GH:IJ:KL
您可以向輸入元素添加一個輸入事件,該事件觸發一個組件方法,該方法將重新格式化其值,如下所示:
模板:
<input (input)="reformat($event) />
零件:
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:");
}
}
正則表達式解釋:
/../g
Javascript 正則表達式文字語法,帶有與所有出現的正則表達式匹配的全局標志
()
- 我們稍后將引用為 $1 的選擇組
[^:]
- 除冒號外的每個字符
{2}
- 前面的表達式應該出現兩次
(?::)
- 前面的表達式后面不應有冒號 \
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.