Function changing the string

Asked

Viewed 55 times

0

I wanted a function that received a string and returned another string with the characters offset 4 times.

For example:

"aaaa" returns "eeee"

"amor" returns "eqsv"

Thank you.

  • What you’ve been trying to?

  • I thought I’d create a vector that holds all the chars, then look for one and return it from position 4 forward. but I don’t think that’s a good approach.

  • 1

    If the function receives zzzz what must return?

  • if it’s zzzz should return dddd. behavior has to be cyclical

1 answer

4


Just add charCode to the desired amount, and then check which character that number equals:

function trocar(){
  var s = document.getElementById('seutexto').value;
  var q = document.getElementById('quant').value;
  var newstring = "";
  for(let i = 0; i < s.length; i++){
    //pega o charCode do caracter e soma
    var quant_troca = parseInt(q);
    var caracter = parseInt(s[i].charCodeAt(0));
    var aux = (caracter + quant_troca);
    //Verifica se ultrapassou os charcodes referentes a caracteres
    if(aux > 122)
    {
      //se passar do z, volta para o a
      aux = 97 + (quant_troca - (123 - caracter));
    }
    //concatena na nova string o caracter equivalente
    newstring += String.fromCharCode(aux);
  }
  alert(newstring);
}
Digite o texto:<input id="seutexto" type="text"></input><br>
Digite a quantidade a deslocar<input id="quant" type="text"><br>
<br>
<button id="trocar" onclick="trocar()">Deslocar</button>

  • good! did not know this function! ta not 100% pq is not cyclic, but I got the idea

  • @J.Guilherme I arranged for it to be cyclical

Browser other questions tagged

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