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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…