Home > Net >  Clear out field when doesn't match condition in React
Clear out field when doesn't match condition in React

Time:06-15

I have two fields. The "Name" and the "Display Name". I wanted to extract only digits to be displayed to the "Display Name". My problem is when I try to remove the digits on the "Name", the "Display Name" looks broken.

Codesandbox

<Box
      component="form"
      sx={{
        "& > :not(style)": { m: 1, width: "25ch" }
      }}
      noValidate
      autoComplete="off"
    >
      <TextField
        label="Name"
        variant="outlined"
        onChange={(e) => setValue(e.target.value)}
        value={value}
      />

      <TextField
        disabled
        label="Display Name"
        variant="outlined"
        value={value && value?.match(/\d /g)?.join("")}
      />
    </Box>

CodePudding user response:

I think is it because of your regular expression. Maybe try something like this

value={value && value?.replace(/[^0-9]/g,'')}

It also basically rips off anything that is not a digit in your input fields.

CodePudding user response:

I use the replace method for extracting number from a string.

const str = 'hello 123 world';

const replaced = str.replace(/\D/g, ''); //            
  • Related