Palindrome in sentences

0

Good, I have a small exercise done in javascript in which determines if a word entered by keyboard is palidrome or not. With words if it works correctly, but when I enter a sentence, it always jumps me with the fact that it is not palindrome.

Code:

function palindromo() {
  var texto;
  var alReves;

  texto = prompt("Introduce texto o palabra: ");
  alReves = cambiar(texto);

  if (texto == alReves) {
    document.write("Palindromo");
  } else {
    document.write("No palindromo");
  }
}

function cambiar(texto) {
  return texto.split("").reverse().join("");
}

palindromo();
    
asked by Mario Guiber 08.01.2018 в 16:26
source

2 answers

2

Good, according to the annotations of @blonfu I show you an example where:

  • Spaces are removed
  • It is all lowercase
  • Accents are removed (from Spanish).
  • function palindromo() {
      var texto;
      var alReves;
    
      texto = getCadenaSinAcentos(prompt("Introduce texto o palabra: ").replace(/\s/g, '').toLowerCase());
      alReves = cambiar(texto);
    
      if (texto == alReves) {
        document.write("Palindromo");
      } else {
        document.write("No palindromo");
      }
    }
    
    function cambiar(texto) {
      return texto.split("").reverse().join("");
    }
    
    function getCadenaSinAcentos(cadena) {
      // Quitamos acentos.
      cadena = cadena.replace(/á/gi, "a");
      cadena = cadena.replace(/é/gi, "e");
      cadena = cadena.replace(/í/gi, "i");
      cadena = cadena.replace(/ó/gi, "o");
      cadena = cadena.replace(/ú/gi, "u");
      return cadena;
    }
    
    
    palindromo();
        
    answered by 08.01.2018 / 17:27
    source
    0

    It may be an uppercase problem since "Apa" is not equal to "apA". Try to do this, but I will try to offer you something else.

    function palindromo()
    {
        var texto;
        var alReves;
    
        texto = prompt("Introduce texto o palabra: ");
        alReves = cambiar(texto);
    
        if(texto.toLowerCase() == alReves.toLowerCase())
        {
            document.write("Palindromo");
        }
        else
        {
            document.write("No palindromo");
        }
    }
    
    function cambiar(texto)
    {
        return texto.split("").reverse().join("");
    }
    
        
    answered by 08.01.2018 в 16:40