Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to remove white space from first and last in react

I don’t want any space before the input and after the input like " text" and "text " does not allow so I replace the white space but when we copy "text " from notepad and paste over the input and want to remove the space it throws error like "can not read property of undefined reading target".so how to do like when user give space front and back its automatically replace whitespace

  const handleKeyDown = (e) => {
    if (e.key === " ") {
      e.preventDefault();
    }
    
  };
  const handleChangeWhiteSpace = (e) => {
    if (e.target.value.includes(" ")) {
      e.target.value = e.target.value.replace(/\s/g, "");
    }
  };

<MyInput
                          type="text" style={{width:'240px'}}
                          error={formik.errors.input && formik.touched.input}
                          value={formik.values.input}
                          onBlur={formik.handleBlur}
                          onChange={(e)=>{formik.handleChange(e);handleChangeWhiteSpace()}}
                          onKeyDown={handleKeyDown}
                          name="input"
                          id="input"
                          autoFocus={false}
                          autoComplete="off"
/>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using regex the following should work, you can test it at regex101:

e.target.value = e.target.value.replace(/^[ \t]+|[ \t]+$/gm, "");

the cleaner solution would be what sojin suggested

e.target.value = e.target.value.trim()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading