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

7

32

I've searched here and there, and I am not able to find something specific about formatting a phone number.

Currently, I am retrieving phone numbers form a JSON in the following format:

25565115

However, I want to achieve this result:

02-55-65-115

For that, I believe that I need to use a custom pipe and I don't think that there is a built-in one that does it automatically.

Can you please give me some guidance on how to do so?

Manse answered 27/4, 2016 at 16:17 Comment(0)
G
30

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.

Gait answered 27/4, 2016 at 16:30 Comment(1)
I your component where you pass PhonePipe, don't you have to import it first like this? import {PhonePipe} from './pipe'Selfdefense
M
21

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();
  }
}
Mullah answered 5/10, 2016 at 12:26 Comment(1)
This works much better than the accepted one. I works perfectly for me after I trim all the extra characters by using var value = tel.toString().trim().replace(/^\+|-|\(|\)/g, '') instead.Tuckie
C
19

When formatting phone numbers from a JSON data service, this was the simplest solution I could think of.

<p>0{{contact.phone.home | slice:0:1}}-{{contact.phone.home | slice:1:3}}-{{contact.phone.home | slice:3:5}}-{{contact.phone.home | slice:5:8}}</p>

This will format "25565115" into "02-55-65-115"

Hope this helps someone!

Cyanite answered 2/5, 2017 at 14:33 Comment(2)
Nice and simple!Ebon
KISS, Keep ISS.Kenji
H
15

I just bumped myself on this article showing how to do that using a Google's lib called libphonenumber. It seems they use this lib in many different languages and has a very wide support (the link is just to the JS package version). Here's how I've implemented it to portuguese / brazilian phone numbers:

First:

npm i libphonenumber-js

Then:

# if you're using Ionic
ionic generate pipe Phone

# if you're just using Angular
ng generate pipe Phone

Finally:

import { Pipe, PipeTransform } from '@angular/core';
import { parsePhoneNumber } from 'libphonenumber-js';

@Pipe({
  name: 'phone'
})
export class PhonePipe implements PipeTransform {
  transform(phoneValue: number | string): string {
    const stringPhone = phoneValue + '';
    const phoneNumber = parsePhoneNumber(stringPhone, 'BR');
    const formatted = phoneNumber.formatNational();
    return formatted;
  }
}

You can implement many different ways with this lib. There's many, many handy methods on it, you can just go reading and see how it suits you.

Thumbs up if you've liked. =]

Humperdinck answered 21/12, 2018 at 18:29 Comment(1)
true, it's reckless to use a formatter of 10 lines' code. there's so much to phone numbers in terms of regions and rules... we should probably use google's lib. I used it a few years back and there were many details I learned while implementing itOlva
S
4

Simple solution with regex to convert the number 25565115 to this 02-55-65-115

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

@Pipe({
  name: "phone"
})
export class PhonePipe {
  transform(value: string): string {
    return value.replace(/(\d{1})(\d{2})(\d{2})(\d{3})/, '0$1-$2-$3-$4');
  }
}
Saltandpepper answered 12/3, 2021 at 19:32 Comment(0)
T
3

You may use something like that in a custom Angular2 pipe:

switch (value.length) {
  case 10: 
    country = 1;
    city = value.slice(0, 3);
    number = value.slice(3);
    break;
  
  case 11: 
    country = value[0];
    city = value.slice(1, 4);
    number = value.slice(4);
    break;
  
  case 12: 
    country = value.slice(0, 3);
    city = value.slice(3, 5);
    number = value.slice(5);
    break;
  
  default:
    return tel;
}

Check this AngularJS out for more info, but as I said you need to convert it to Angular2:

http://jsfiddle.net/jorgecas99/S7aSj/

Tomaso answered 27/4, 2016 at 16:23 Comment(0)
C
0

Here is how I did it:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'usPhone'
})
export class USPhonePipe implements PipeTransform {
  private readonly PHONE_REGEX = /^(\d{3})(\d{3})(\d{4})$/;
  private readonly PHONE_PREFIX = /\+?(1)?/;
  private readonly SPACES = /\s+/g;

  transform(value: string): string {
    let trimmed = value.replace(this.SPACES, '');
    trimmed = trimmed.replace(this.PHONE_PREFIX, '');

    const matches = trimmed.match(this.PHONE_REGEX);

    if (!matches) {
      return value;
    }

    const phoneParts = matches.slice(1,);
    return phoneParts.join('-');
  }
}

But in my case I needed it to be like: +19998887766 -> 999-888-77-66

Convulsive answered 25/2, 2023 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.