简体   繁体   中英

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

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.

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 ^([AZ]{2})([AZ]{1,3})?(\d{1,6})?$ :

  • ^ - start of string
  • ([AZ]{2}) - Group 1: two uppercase letters
  • ([AZ]{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 = /^([AZ]{2})([AZ]{1,3})?(\d{1,6})?$/; $('body').on('input', '.demo', function(e) { this.value = this.value.replace(/[^AZ\d]+/g,'').replace(/^([AZ\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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM