3
I need to make a Javascript function that when clicking the button check if a specific character was typed, in this case the '
(single quotes). If yes, replace the single quote with a blank.
See the code below:
const charValidation = ()=> {
let inputToValidate = document.querySelectorAll(".area-input input");
for(i=0;i<inputToValidate.length;i++) {
let inputZin = inputToValidate[i].value;
if(inputZin.match(["\'"])) {
let inputEr = inputZin.replace(/\'/g, "");
inputZin.innerHTML = inputEr;
}
}
}
<span class="area-input">
<input type="text" placeholder="nome" title="não permitido caracteres especiais">
</span>
<span class="area-input">
<input type="text" placeholder="telefone" title="apenas números">
</span>
<span class="area-input">
<input type="text" placeholder="endereço" title="não permitido caracteres especiais">
</span>
<input type="button" onclick="charValidation()" value="OK">
I was thinking of getting rid of match
and simply replace direct.
Wouldn’t it be better to use
replace("'", " ")
instead of compiling a Regexp each time?– fernandosavio
Not because otherwise it will only replace 1 occurrence.
– Sam
Whoo, I fell for that trick. It’s true!
– fernandosavio
all the answers worked, but I liked your code and the tips better! now I will always use a Let or const before the variable in the loop "for" thank you very much!
– MSHijo