Home > other >  I want to replace first 2 digits of number by XXX in angular template
I want to replace first 2 digits of number by XXX in angular template

Time:11-23

I have inputs like 999,9999,10999. I want to replace first digits except last two by XXX in angular template. That is 999 should become X99,9999 should XX99 and 10999 should XXX99.

How to do that is there any pipe?

CodePudding user response:

I writed my own pipe

Since I am from india there is another code which will convert input to indian currency format. (You can remove that part if it is not necessary for you.)

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

@Pipe({
  name: 'xMask'
})
export class XMaskPipe implements PipeTransform {

 transform(value: number): any {

if ((!isNaN(value)) && (value != 0)) {
  var currencySymbol = '₹';
  //var output = Number(input).toLocaleString('en-IN');   <-- This method is not working fine in all browsers!           
  var result = value.toString().split('.');

  var lastThree = result[0].substring(result[0].length - 3);
  var otherNumbers = result[0].substring(0, result[0].length - 3);
  if (otherNumbers != '')
    lastThree = ','   lastThree;
  var output = otherNumbers.replace(/\B(?=(\d{2}) (?!\d))/g, ",")   lastThree;

  if (result.length > 1) {
    output  = "."   result[1];
  }

  const visibleDigits = 2;
  let maskedSection = output.slice(0, -visibleDigits);
  let visibleSection = output.slice(-visibleDigits);
  return currencySymbol   maskedSection.replace(/./g, 'X')   visibleSection;
    }

  }



}

CodePudding user response:

You can simply do with a Pipe,

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'specialPipe'
})
export class specialPipe implements PipeTransform {

  transform(value: string): string {
    let newVal = value.replace(/\d{2}$/, 'XX');
    return newVal;
  }
  
}

and use it as,

<hello name="{{ name1 |specialPipe }}"></hello>

DEMO

  • Related