Skip to content

Instantly share code, notes, and snippets.

@porqz
Created January 22, 2018 11:58
Show Gist options
  • Save porqz/b6d7074e26f66dade079ea8ed0a57aff to your computer and use it in GitHub Desktop.
Save porqz/b6d7074e26f66dade079ea8ed0a57aff to your computer and use it in GitHub Desktop.
import { Pipe, PipeTransform } from '@angular/core';
interface ParsedPhone {
code: string;
mainPart: string;
}
@Pipe({
name: 'prettifyPhone'
})
export class PrettifyPhonePipe implements PipeTransform {
public transform(value: string, args: string[]): string {
if (!value) { return value; }
return this.prettify(value);
}
private parse(phone: string): ParsedPhone {
let code = '';
let mainPart = '';
const normalizedPhone = phone.replace(/\s|-|\(|\)/g, '');
const normalizedPhoneWithoutPrefix = normalizedPhone.replace(/^(\+7|8)/, '');
const matchedCode = /\((\d+)\)/.exec(phone.replace(/\s|-/g, ''));
if (matchedCode) {
code = matchedCode[1];
} else {
if (
normalizedPhoneWithoutPrefix.length === 10 &&
(normalizedPhoneWithoutPrefix[0] === '9' || normalizedPhoneWithoutPrefix.indexOf('800') === 0)
) {
code = normalizedPhoneWithoutPrefix.slice(0, 3);
}
}
mainPart = normalizedPhoneWithoutPrefix.replace(code, '');
return {
code,
mainPart
};
}
private prettify(phone: string): string {
const { code, mainPart } = this.parse(phone);
let prefix = '';
let formattedCode = '';
let formattedNumber = '';
if (code.length > 0) {
// По умолчанию рассматриваем код, как код города
formattedCode = `(${code}) `;
if (code.length === 3) {
// Если мобильний
if (code[0] === '9') {
prefix = '+7 ';
formattedCode = `${code} `;
}
// Если 8-800-
if (code === '800') {
prefix = '8 ';
formattedCode = `${code} `;
}
}
}
// Разбиваем основную часть номера на группы
const matchedNumberGroups = mainPart.match(/(\d{0,3})(\d{2})(\d{2})/);
formattedNumber = matchedNumberGroups
? `${matchedNumberGroups[1]}-${matchedNumberGroups[2]}-${matchedNumberGroups[3]}`
: mainPart;
return `${prefix}${formattedCode}${formattedNumber}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment