Add a space every 4 characters in input with a Pipe

Issue

I have an input where a user needs to insert 24 characters. I tried to make a pipe with regExp to do this but no spaces are added.

Ive seen functions that could do this but I wanted to keep it simple with regExp.

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

@Pipe({
  name: 'formatBankAcc'
})

export class FormatBankAccPipe implements PipeTransform {
  transform(value: string) {
    if(value != null){
      value.replace(/[^\dA-Z]/g, '')
      .replace(/(.{4})/g, value)
      .trim();
      console.log(value);
    }
    return value;
  }
}

Solution

The issue here is you are actually no adding any space in your regex. Instead, you are replacing the text again with same value. Also, you are not updating the value with replaced value. You are just returning the current value only like:

function transform(value) {
  if (value != null) {
    value.replace(/[^\dA-Z]/g, '')
      .replace(/(.{4})/g, value)
      .trim();
    console.log(value);
  }
  return value;
}

transform('123456789') //=> 123456789 ... returns same value

To fix this you need to:

  1. Add a space after each matching group like:

    .replace(/(.{4})/g, '$1 ')
    

    $1 here represents the 1st capture group of the regular expression.

  2. Then update the value with new replaced value like:

    value = value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
    
function transform(value) {
  if (value != null) {
    value = value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
    console.log(value);
  }
  return value;
}

transform('123456789')  
//=> 1234 5678 9 ... returns value w/ a space every 4 character

Answered By – palaѕн

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.