skip to Main Content

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" />

2

Answers


  1. 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" />
    Login or Signup to reply.
  2. The issue with your code is that you’re applying the replace and trim methods to the string @gmail.com, not to the value of input1. You should apply these methods to input1.value instead. Here’s the corrected code:

    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.replace(/s+/g,'').trim() + "@gmail.com";
    });
    

    In this code, replace(/s+/g,'').trim() is applied to input1.value, which removes all spaces from the input and trims any leading or trailing spaces. Then, @gmail.com is appended to the result.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search