Replace special characters and uppercase letters

Asked

Viewed 3,472 times

2

I have this code that copies everything you type into one input to another, I want when it copies to the other input replace special characters, spaces with "-" and minute letters. How could I do like 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">

Input example: Ação Esperada

Expected exit: acao-esperada

  • Have you tried using the str.replace javascript?

  • $('.mirror'). on('keyup', Function() { $str.replace(('. '+$(this). attr('class')). val($(this). val()); });

  • You want to replace such characters with what? Yours replace doesn’t seem to make sense. Have you read the documentation of function?

  • You can give an example of the text you want to replace and how it should look?

  • Expected action expected action

4 answers

2

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

In the arrays find and replace can configure 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>

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

  • If you type "action", the expected result is "action", such as commented.

1

From what I understand, you want to create a kind of Slug in the second input from the data entered in the first. For 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"));

Function based on this reply in the Soen.

That is, using with the 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>

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

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

  • He also wants to replace the special characters with the tracine ( - ). Now I ask you what is special character?

  • @Leocaracciolo, no. See his comment on the question. I added the example in the question body to avoid confusion.

  • blz, now I’ve seen the comment, I’ll have to work harder right :)

  • @Leocaracciolo On the ç, I believe so, because it is not in the ASCII table. I don’t know exactly the purpose of removing these characters in this context, but assuming that it will be used somewhere that does not support these characters, there would also be no support for the ç.

  • understood, your explanation has everything to do, thanks

0

Thus uses 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">
  • he doesn’t copy from the other side with that code

  • I changed the answer for you @Wagnermartinsbodyboard

  • I chewed there for you @Wagnermartinsbodyboard . I added an "id" and removed the class "mirror" in "two".

-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 in input id=two as you would do?

  • Change the selector in jQuery to its id.

  • can you tell me how I do it?

  • $('#two.'+$(this).attr('class')).val(res); Alternatively, because this event runs on an element whose class is mirror, only $('#two.mirror').val(res); already resolves...

Browser other questions tagged

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