Skip to content

Instantly share code, notes, and snippets.

@carlitomurta
Created November 22, 2019 14:14
Show Gist options
  • Save carlitomurta/bc58d524b03d20c81bf0c22ac7c91db7 to your computer and use it in GitHub Desktop.
Save carlitomurta/bc58d524b03d20c81bf0c22ac7c91db7 to your computer and use it in GitHub Desktop.
Pipe Angular para CEP/ZipCode
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'zipCode'
})
export class ZipCodePipe implements PipeTransform {
transform(value: string, args?: any): any {
if (value) {
value = value.replace(/\D/g, '');
if (value.length > 8) {
value = value.substring(0, 8);
}
switch (value.length) {
case 3:
value = value.replace(/(\d{2})(\d+)/, '$1.$2');
break;
case 4:
value = value.replace(/(\d{2})(\d+)/, '$1.$2');
break;
case 5:
value = value.replace(/(\d{2})(\d+)/, '$1.$2');
break;
case 6:
value = value.replace(/(\d{2})(\d{3})(\d+)/, '$1.$2-$3');
break;
case 7:
value = value.replace(/(\d{2})(\d{3})(\d+)/, '$1.$2-$3');
break;
case 8:
value = value.replace(/(\d{2})(\d{3})(\d+)/, '$1.$2-$3');
break;
default:
return value;
}
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment