Angular 2: pipes - How to format a phone number?

StackBlitz

pipe implementation in TS would look like this

import { Pipe } from "@angular/core";

@Pipe({
  name: "phone"
})
export class PhonePipe {
  transform(rawNum) {
    rawNum = rawNum.charAt(0) != 0 ? "0" + rawNum : "" + rawNum;

    let newStr = "";
    let i = 0;

    for (; i < Math.floor(rawNum.length / 2) - 1; i++) {
      newStr = newStr + rawNum.substr(i * 2, 2) + "-";
    }

    return newStr + rawNum.substr(i * 2);
  }
}

Declare the PhonePipe in your NgModule's declarations


Usage:

import {Component} from 'angular/core';

@Component({
  selector: "my-app",
  template: `
    Your Phone Number: <input [(ngModel)]="myNumber" />
    <p>
      Formatted Phone Number: <b>{{ myNumber | phone }}</b>
    </p>
  `
})
export class AppComponent {
  myNumber = "25565115";
}

There are many things that can be improved, I just made it work for this particular case.


Building on "user5975786", here is the same code for Angular2

import { Injectable, Pipe } from "@angular/core";

@Pipe({
  name: "phone",
})
export class PhonePipe {
  transform(tel, args) {
    var value = tel.toString().trim().replace(/^\+/, "");

    if (value.match(/[^0-9]/)) {
      return tel;
    }

    var country, city, number;

    switch (value.length) {
      case 10: // +1PPP####### -> C (PPP) ###-####
        country = 1;
        city = value.slice(0, 3);
        number = value.slice(3);
        break;

      case 11: // +CPPP####### -> CCC (PP) ###-####
        country = value[0];
        city = value.slice(1, 4);
        number = value.slice(4);
        break;

      case 12: // +CCCPP####### -> CCC (PP) ###-####
        country = value.slice(0, 3);
        city = value.slice(3, 5);
        number = value.slice(5);
        break;

      default:
        return tel;
    }

    if (country == 1) {
      country = "";
    }

    number = number.slice(0, 3) + "-" + number.slice(3);

    return (country + " (" + city + ") " + number).trim();
  }
}