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
You’re removing spaces from
@gmail.com
, not the user’s input. It should beinput1.value.replace(...)
.The issue with your code is that you’re applying the
replace
andtrim
methods to the string@gmail.com
, not to the value ofinput1
. You should apply these methods toinput1.value
instead. Here’s the corrected code:In this code,
replace(/s+/g,'').trim()
is applied toinput1.value
, which removes all spaces from the input and trims any leading or trailing spaces. Then,@gmail.com
is appended to the result.