Function that changes the string [closed]

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.

    
asked by anonymous 12.07.2017 / 16:12

1 answer

4

Simply add the desired quantity to charCode, and then check which character this number is equivalent to:

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>
    
12.07.2017 / 16:28