Replace special characters and capital letters

2

I have this code that copies everything that is typed in one input to another, I want it to copy to the other input replace special characters, spaces with "-" and lowercase . How could I do as jquery?

$('.mirror').on('keyup', function() {
    $('.'+$(this).attr('class')).val($(this).val());
})


<input type="text" class="mirror" placeholder="one">
<input type="text" class="mirror" placeholder="two">

Example input: Ação Esperada

Expected output: acao-esperada

    
asked by anonymous 29.06.2017 / 17:47

4 answers

2

Using Regular Expression /[^\w\s]/gi, '-' to replace special characters with (-) and then the toLowerCase() function to transform into lowercase letters we will reach the expected result.

  

In arrays find and replace you can set the characters to be replaced respectively.

$(document).ready(function() {
$('.mirror').on('keyup', function() {
 
 var v1 = document.getElementById("codigo").value ;
    
 var find = ["ã","à","á","ä","â","è","é","ë","ê","ì","í","ï","î","ò","ó","ö","ô","ù","ú","ü","û","ñ","ç"]; "à","á","ä","â","è","é","ë","ê","ì","í","ï","î","ò","ó","ö","ô","ù","ú","ü","û","ñ","ç"
 var replace = ["a","a","a","a","a","e","e","e","e","i","i","i","i","o","o","o","o","u","u","u","u","n","c"];

    for (var i = 0; i < find.length; i++) {
        v1 = v1.replace(new RegExp(find[i], 'gi'), replace[i]);
    }

    var desired = v1.replace(/\s+/g, '-');
    desired = desired.toLowerCase();

    var v2 = document.getElementById("copia").value = desired;
    
});   
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="codigo" class="mirror" placeholder="one">
<input type="text" id="copia" class="mirror" placeholder="two">
    
29.06.2017 / 22:02
1

From what I understand, you want to create a sort of slug in the second input from the data reported in the first. To do this, use the function below:

function slugify(str) {
  
  // Converte o texto para caixa baixa:
  str = str.toLowerCase();
  
  // Remove qualquer caractere em branco do final do texto:
  str = str.replace(/^\s+|\s+$/g, '');

  // Lista de caracteres especiais que serão substituídos:
  const from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
  
  // Lista de caracteres que serão adicionados em relação aos anteriores:
  const to   = "aaaaaeeeeeiiiiooooouuuunc------";
  
  // Substitui todos os caracteres especiais:
  for (let i = 0, l = from.length; i < l; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  // Remove qualquer caractere inválido que possa ter sobrado no texto:
  str = str.replace(/[^a-z0-9 -]/g, '');
  
  // Substitui os espaços em branco por hífen:
  str = str.replace(/\s+/g, '-');

  return str;
};

console.log(slugify("Ação Esperada"));
  

Role based on what is presented in this SOen.

That is, using with input :

function slugify(str) {
  
  // Converte o texto para caixa baixa:
  str = str.toLowerCase();
  
  // Remove qualquer caractere em branco do final do texto:
  str = str.replace(/^\s+|\s+$/g, '');

  // Lista de caracteres especiais que serão substituídos:
  const from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
  
  // Lista de caracteres que serão adicionados em relação aos anteriores:
  const to   = "aaaaaeeeeeiiiiooooouuuunc------";
  
  // Substitui todos os caracteres especiais:
  for (let i = 0, l = from.length; i < l; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }

  // Remove qualquer caractere inválido que possa ter sobrado no texto:
  str = str.replace(/[^a-z0-9 -]/g, '');
  
  // Substitui os espaços em branco por hífen:
  str = str.replace(/\s+/g, '-');

  return str;
};

$(function () {

  $("#input-one").on("keyup", function (event) {
  
      $("#input-two").val(slugify($(this).val()));
  
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="input-one" class="mirror" placeholder="one">
<input type="text" id="input-two" class="mirror" placeholder="two">

Notice that I set the id attribute for each field and used it to properly select the field I want to get or change the value.

    
29.06.2017 / 20:47
0

Use the substrig / replace:

$('.mirror').on('keyup', function() {
    var str = $(this).val();
    str = str.replace(".", "");
    str = str.replace(",", ""); //Tu adicionas todos os caracteres que tu queres remover.
    var res = str.replace("#", ""); //E no último, joga na variável 'res'
    $("#novoTexto").val(res);
})

<input type="text" class="mirror" placeholder="one">
<input id="novoTexto" type="text" placeholder="two">
    
29.06.2017 / 18:59
-1
$('.mirror').on('keyup', function() {
    var str = $(this).val();
    var res = str.replace(" ", "-");
    $('.'+$(this).attr('class')).val(res).val();
})

I did so now it changes nois two inputs I want to change only the input id = two how would I do it?

    
29.06.2017 / 20:05