Home > Blockchain >  Format a license number while entering the text in a textbox using regular expression in javascript
Format a license number while entering the text in a textbox using regular expression in javascript

Time:10-02

Here is my React code that can do the conversion but I need a bit of modification in the current approach is The conversion should be as and when I keep typing.

Below is my current code....

import React, { useEffect, useState } from 'react';
import './styles.css';

export default function App() {
  const [keyword, setKeyword] = useState('');

  const formatInput = (e) => {
    setKeyword(e.target.value);
  };

  const normalize = (keyword) => {
    if (keyword.length <= 13) {
      setKeyword(keyword.replace(/([A-Z]{2})([A-Z]{3})(\d{6}$)/, '$1-$2-$3'));
    }

    return null;
  };

  useEffect(() => {
    normalize(keyword);
  });

  return (
    <div className="App">
      <input type="text" placeholder="enter string" onChange={formatInput} />

      {keyword}
    </div>
  );
}

// DL-HGK-123456

Expected out should be as below...

For Example:

DLHGK to be converted to Dl-HGK
DLHGK12 to be converted to DL-HGK-12

as an when we are typing the input in our input box.

Thanks for the help.

CodePudding user response:

You can use

keyword.replace(/[^A-Z\d] /g,'')        // Remove any non-alphanumeric entered
   .replace(/^([A-Z\d]{11}).*/, '$1')   // Keep only 2 3 6=11 max chars
    .replace(/^([A-Z]{2})([A-Z]{1,3})?(\d{1,6})?$/, (_,x,y,z) =>           
      z ? `${x}-${y}-${z}` :
      y ? `${x}-${y}` : x );            // Format the output

The main regex is ^([A-Z]{2})([A-Z]{1,3})?(\d{1,6})?$:

  • ^ - start of string
  • ([A-Z]{2}) - Group 1: two uppercase letters
  • ([A-Z]{1,3})? - Group 2 (optional): one to three uppercase letters
  • (\d{1,6})? - - Group 3 (optional): one to six digits
  • $ - end of string.

See the JavaScript demo:

const rx = /^([A-Z]{2})([A-Z]{1,3})?(\d{1,6})?$/;

$('body').on('input', '.demo', function(e) {
  this.value = this.value.replace(/[^A-Z\d] /g,'')
   .replace(/^([A-Z\d]{11}).*/, '$1')
    .replace(rx, (_,x,y,z) =>
      z ? `${x}-${y}-${z}` :
      y ? `${x}-${y}` : x );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="demo" maxlength=13>

Note that maxlength is set to 13 here, 11 chars 2 hyphens.

  • Related