Home > Enterprise >  Using regex to place dashes at specific indexes of a string containing numbers and letters
Using regex to place dashes at specific indexes of a string containing numbers and letters

Time:05-04

So the formatted code needs looks like this:

"US-XXX-12-12345"

So that's two letters, followed by 3 letters/numbers, followed by 2 numbers, then followed by 5 letters/numbers. I was able to get it to work using only numbers with the following:

return testString
  .replace(/(\d{2})(\d)/, '$1-$2')
  .replace(/(\d{3})(\d)/, '$1-$2')
  .replace(/(\d{2})(\d{2})/, '$1-$2')
  .replace(/(\d{4})(\d{2})/, '$1-$2')

This returns:

"12-345-67-89012" 

I tried switching the lowercase d's for uppercase ones (representing letters) and it adds all sorts of extra dashes and does not let me backspace. Any and all help is much appreciated!

CodePudding user response:

I would use a function like this:

function mask(string, model){
    let i = 0;
    return model.replace(/#/g, () => string[i  ] || "");
}

use:

mask("USXXX1212345", "##-###-##-#####") => 'US-XXX-12-12345'

the first parameter of the function is the string you want to format, and the next parameter is how it will be formatted

CodePudding user response:

This isn't quite what you asked for but regex probably isn't the best solution to this question. A better option would probably be to use something like react-input-mask because you mentioned using this in real time in a React form.

import { useState } from "react";
import InputMask from "react-input-mask";

const Example = () => {
  const [inputText, setInputText] = useState("");

  return (
    <InputMask
      mask="aa-***-99-*****"
      value={inputText}
      onChange={(e) => setInputText(e.target.value)}
    />
  );
};

And here's a CodeSandbox example because I can't for the life of my embed a functional example in a SO answer: https://codesandbox.io/s/react-input-mask-example-554lcn?file=/src/App.js

  • Related