javascripthtmlreactjsinputspace

Limit spaces in input HTML field


I'm writing a website using React and I've encountered an interesting problem.

I have a simple component in which the user can enter text. This component is implemented using an HTML input field.

 const Title = () => {
  return (
      <span>
        Name title
      </span>
      <input
        id="name_title"
        onChange={(event) => setNameTitle(event.target.value)}
        value={NameTitle}
      />
  );
};

export default Title;

My problem is handling spaces. By default, spaces are not processed in any way and, accordingly, the user can enter any number of them. But as you understand, this is not correct. I would like to :

  1. Prohibit starting input in a field with spaces. That is, so that the user cannot enter a space as the first character in the field;
  2. Limit the number of spaces between words. No more than one. That is, a space cannot be followed by a space.

I think this is a very useful thing, but unfortunately I found absolutely no information on this issue. Tell me how to solve this problem


Solution

  • In JavaScript, you can use String.prototype.trimStart() function to get rid of whitespaces from the beginning of the string. To get rid of any whitespaces in the string (for the spaces in between words), you would need to use String.prototype.replace() function to replace whitespaces with length of more than 1 characters (by using a regular expression).

    This line of code should do the trick:

    onChange={(event)=>setNameTitle(event.target.value.trimStart().replace(/\s+/g, " ")

    Firstly, you are removing the whitespaces at the beginning of the string with trimStart() function and then you are removing whitespaces (denoted by "\s" in regular expressions) recurring one or more times (denoted by "+" in regular expressions) for all the occurances in that string (denoted by "g") with " " character. However, if you are submitting the value in that input to a function or a web server, this won't get rid of the last singular whitespace in that string (if it exists). Thus, before submitting, make sure to use NameTitle.trimEnd() to get rid of the final whitespace character in that string (if it exists).