Remove spaces in the input fields

1

Colleagues.

I have a form that I would like the user to copy a particular word and paste in the input field, remove the spaces between the phrase or word copied automatically. Would you have any means in CSS or Javascript?

    
asked by anonymous 06.01.2017 / 14:37

4 answers

5

So:

<input type="text" id="t" />

<script>
var $t = document.getElementById('t');
$t.addEventListener('paste', function(event) {
  setTimeout(function(){
    this.value = this.value.replace(/\s+/g, '');
  }.bind(this), 0)
});
</script>

edit: If you just want the spaces before and after, just change the regex to:

.replace(/^\s+|\s+$/g, '')
    
06.01.2017 / 14:46
4

Based on in this answer , we can see that using HTML and JS is possible. Here's how:

HTML

<input type="text" id="telefone" maxlength="10" />​

JavaScript

var telefone = document.getElementById('telefone'),
    limparEspacos;

limparEspacos= function(e) {
    e.preventDefault();
    var pastedText = '';
    if (window.clipboardData && window.clipboardData.getData) { // IE
        pastedText = window.clipboardData.getData('Text');
      } else if (e.clipboardData && e.clipboardData.getData) {
        pastedText = e.clipboardData.getData('text/plain');
      }
    this.value = pastedText.replace(/\D/g, '');
};

telefone.onpaste = limparEspacos;

Remembering that regex responsible for removing the spaces is in this line:

this.value = pastedText.replace(/\D/g, '');

That is, if you want to change some other character, you must change the mask /\D/g , within .replace(/\D/g, ''); to match the characters you want.

    
06.01.2017 / 14:56
3

You can use the paste event. Then separate by spaces and then join without them:

function removerEspacos(e) {
  var clipboardData, pastedData;

  e.stopPropagation();
  e.preventDefault();

  clipboardData = e.clipboardData || window.clipboardData;
  pastedData = clipboardData.getData('Text');

  document.getElementById('entrada').value = pastedData.split(' ').join('');
}

document.getElementById('entrada').addEventListener('paste', removerEspacos);
<input id="entrada" />
    
06.01.2017 / 14:55
2

var input = document.querySelector('input');
var palavras = ['palavra1', 'palavra2'];

function limpar() {
  var self = this;
  palavras.forEach(function(palavra) {
    var regex = new RegExp('\s*' + palavra + '\s*', 'g');
    self.value = self.value.split(regex).join(palavra);
  });
}

input.addEventListener('keyup', limpar);
input.addEventListener('paste', limpar);

/* Texto para testar:

Olá este texto tem a palavra1 no meio.

Este texto tem a palavra2, e também a palavra1 misturadas.

*/
input {
  width: 300px;
  padding: 5px;
}
<input>

The idea of the code is: every time there is paste or keyup it runs the limpar function that searches the input for each word with or without space before and after in the text. If it finds you remove the space and join the word to what was before and after, taking the spaces.

    
06.01.2017 / 14:55