Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in javascript in a very specific format

I have a input that has to format what's the user typing(actually it is info from his bank account). But the numbers have to be formatted in a certain way:

  • the first 5 digits must be numbers.
  • if the user type more than 5 numbers, the last number must have a '-' before it
  • after the 5 digit, the user can type 'x' or 'X'
  • the number can have minimun of 5 digits, and maximum of 15

examples:

  • 12345
  • 12345-1
  • 123456-1
  • 1234567-1
  • 12345-x
  • 123456789-x
  • 123456789-X
  • 12345678901234-5

Actually I'm using a normalizer that replaces the string.

This is what I'm using but I cant format it correctly.

export const normalizeBankAccount = value => {
    if (!value) {
      return value
    }

    if(value.length <= 16 && (!value.match(/[^\d|X]/g) || !value.match(/[^\d|-]/g) || !value.match(/[^\d|x]/g))) {
      if(value.length <= 5){
        return value.replace(/[^\d]/g, '')
      } else if(value.length >= 6) {
        const len = value.length;
        const aux=value;
        const initial = value.substring(0,value.length-1).replace('-', '');
        console.log("len: " +len, "\naux: " +aux,"\ninitial: "+ initial)
        return value.replace(new RegExp("\\d{"+ len +"}") , initial+ '-').replace(/[X]/g, '-X').replace(/[x]/g, '-x')
      }
    }
}

When I use this method, the string is formatted like this:

  • 12345-6789123
like image 701
Ramon Avatar asked Jun 20 '26 01:06

Ramon


1 Answers

You could look for a given length, followed by a single character and add a minus sign.

const
    normalize = string => string.replace(/^\d{5,14}(?=[0-9x]$)/i, '$&-');

console.log(['12345', '123451', '1234561', '12345671', '12345x', '123456789x', '123456789X', '123456789012345'].map(normalize));

Example with input.

function update(element) {
    element.value = element.value
        .replace(/[^0-9x]/gi, '')
        .replace(/x(?=.)/gi, '')
        .replace(/^\d{5,14}(?=[0-9x]$)/i, '$&-');
}
<input type="text" onkeyup="update(this)" id="x">
like image 110
Nina Scholz Avatar answered Jun 22 '26 14:06

Nina Scholz