Search code examples
javascript

The function replace(/\s+/g,' ').trim() and trim() is not good working for input value


I tried to use replace(/\s+/g,' ').trim() as well as just .trim() but it's not working.

I want to remove any spaces typed in input1 from input2 and input3. Please help.

var input1 = document.getElementById('myInput1');
var input2 = document.getElementById('myInput2');
var input3 = document.getElementById('myInput3');

  input1.addEventListener('change', function() {
    input2.value = input1.value + "@gmail.com".replace(/\s+/g,' ').trim();
    input3.value = input1.value + "@gmail.com".trim();
  });
<input type="text" id="myInput1" />
<input type="text" id="myInput2" />
<input type="text" id="myInput3" />


Solution

  • You're removing spaces from @gmail.com, not the user's input. It should be input1.value.replace(...).

    var input1 = document.getElementById('myInput1');
    var input2 = document.getElementById('myInput2');
    var input3 = document.getElementById('myInput3');
    
      input1.addEventListener('change', function() {
        input2.value = input1.value.replace(/\s+/g,' ').trim() + "@gmail.com";
        input3.value = input1.value.trim() + "@gmail.com";
      });
    <input type="text" id="myInput1" />
    <input type="text" id="myInput2" />
    <input type="text" id="myInput3" />