Replace a specific character in a <input type="text">

Asked

Viewed 486 times

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.

4 answers

2


You can do the direct replace without going through the match. The match only serves to verify the existence or capture something and get the result. replace will only replace if the character exists, and if it does not exist, it does nothing and gives no error.

Another thing, the simple quotes need no escape, and if the intention is to replace with a space, it would be " " instead of "". You can also delete some lines of code by passing it all at once, as in the code below:

const charValidation = ()=> {
            let inputToValidate = document.querySelectorAll(".area-input input");
            for(let i=0;i<inputToValidate.length;i++) {
                inputToValidate[i].value = inputToValidate[i].value.replace(/'/g, " ");
            }
        }
<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">

Also put a let in the i of for to restrict the scope of variable only within the for.

  • 1

    Wouldn’t it be better to use replace("'", " ") instead of compiling a Regexp each time?

  • 1

    Not because otherwise it will only replace 1 occurrence.

  • 1

    Whoo, I fell for that trick. It’s true!

  • 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!

2

uses this function

$('input').keypress(function(e){
   if(String.fromCharCode(event.which) == "'"){
       event.preventDefault()
       $(this).val(str + ' '); 
   }
});

where the input you put the class of your field.

1

You can use replace with RegExp:

document.querySelectorAll('.area-input > input').forEach(i => i.value = i.value.replace(/'/g,' '))  

Or split with join:

document.querySelectorAll('.area-input > input').forEach(i => i.value = i.value.split('\'').join(' ')) 

const charValidation = () => {
           
document.querySelectorAll('.area-input > input').forEach(i => i.value = i.value.replace(/'/g,' '))       
        
}

const charValidation2 = () => {
           
document.querySelectorAll('.area-input > input').forEach(i => i.value = i.value.split('\'').join(' '))  
        
}
<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>
<p></p>
<input type="button" onclick="charValidation()" value="com RegExp">
<input type="button" onclick="charValidation()" value="com Split">

  • 1

    po guy I liked this code, it’s completely different than what I had thought. I didn’t know this "foreach" it works the same way as the "for" loop? I’ll give a search! orbigado by help!

  • @Mshijo, both will go through the array element by element, but I find foreach much more intuitive and easy to read, even more if you need to make a loop within another. I only use the is when performance is a concern and break is crucial to it. In foreach there is no such break possibility. You can read about foreach here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

1

Speaks Young , beauty?

Use . each and index ..

I think it works well :)

function charValidation(){

        $(".area-input input").each(function( index ) {
          var str = $(this).val();           
          if(str.indexOf("'") != -1 ){
            str = str.replace(/\'/g, "");
             $(this).val(str);
          }              
        });
}

The each will play the role of the loop :)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script  src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
</head>
<body>
	<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">
</body>
<script>
	
		function charValidation(){

			$(".area-input input").each(function( index ) {
		      var str = $(this).val();		     
		      if(str.indexOf("'") != -1 ){
		      	str = str.replace(/\'/g, "");
		      	 $(this).val(str);
		      } 		     
		    });
		}
	
</script>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.