Search code examples
javascriptreplaceredex

JS regular expressions for fisrt one letter and numbers


I try make regular expression for one letter Z and 12 digits.

event.target.value = event.target.value.replace(/[^Z{1}+(\d{12})]/, '');

It is necessary for me that in the input field it was possible to enter one letter Z and then 12 digits only.

Please help me.


Solution

  • The regexp is

    /^Z\d{12}$/
    
    • ^ matches the beginning of the string
    • Z matches the initial Z. There's no need for {1} since patterns always match exactly one time unless quantified.
    • \d{12} matches exactly 12 digits
    • $ matches the end of the string

    const regex = /^Z\d{12}$/;
    
    console.log(regex.test('Z123456789012')); // true
    console.log(regex.test('X123456789012')); // false - begins with wrong letter
    console.log(regex.test('Z1234567890')); // false - <12 digits
    console.log(regex.test('Z123456A89012')); // false - letter mixed into digits
    console.log(regex.test('Z123456789012345')); // false - >12 digits