Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove white spaces from both ends of a string inside a form - React

I have a simple form that receives the first name and last name, and I need to remove the whitespaces in the beginning and end of the string. I can do this with the .trim() method, but because is a form, it doesn't let me write a name that has two words, such as Ana Maria, because it doesn't let me press the space key at the end of a word. How can I remove white spaces from both sides of a string but still let me press space and write more than one word?

enter image description here

This is the component:

export default function ScheduleInput(
  { label, required, onChange, value, ...extraProps },
) {
  return (
    <div className="item_container">
      {label}:
      {required &&
        <span style={{ color: 'red' }}> *</span>
      }
      <br />
      <input
        type="text"
        onChange={onChange}
        value={value.trim()}
        {...extraProps}
      />
    </div>
  );
}
like image 635
Liz Parody Avatar asked Sep 11 '18 21:09

Liz Parody


People also ask

What removes white space from both ends of a string?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How do I remove extra spaces from string in react?

To remove the empty spaces from the string, use the replace() method in JavaScript. This method searches a string for a specified value and returns a new string replacing those values.

How do you remove spaces from a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.

How do I remove the white space from a string in react native?

“remove space from string react native” Code Answer var noSpacesString= myString. replace(/ /g,'');// "DoIhavespaces?"


1 Answers

Instead of trimming onChange, do that in an onBlur callback:

<input onBlur={this.props.formatInput} {...} />

Where that might look something like this:

formatInput = (event) => {
  const attribute = event.target.getAttribute('name')
  this.setState({ [attribute]: event.target.value.trim() })
}
like image 169
coreyward Avatar answered Sep 29 '22 18:09

coreyward