0

I have to write a script to check if a word entered by a user is a Palindrome. I've gotten as far as validating the word and displaying the number of characters. Also not supposed to use the reverse method.

I've looked at some of the examples here and think I need to turn the user input into a string and use a "for" loop and if/else statement. But how do I turn the user input into a string in order to check each character? This is a total mess but it's all I've got so far:

    function checkWord(userWord3) {
        var answer = "Your word is";

        answer += retrieveWord(userWord3);

        return (answer);
    }

    function retrieveWord(userWord) {
        var string = userWord;
        var i = userWord.length;


        for(var i = 0; i < str.length / 2; i++) {
            alert(str[i], str[str.length -i -1]);
            if( str[i] != str[str.length - i -1] ) {
                return false;
            }
        }
    }
the_dude
  • 1,004
  • 1
  • 11
  • 21
Robin D.
  • 97
  • 8
  • 1
    possible duplicate - http://stackoverflow.com/questions/22111507/how-to-write-palindrome-in-javascript – the_dude Feb 20 '16 at 19:54

3 Answers3

1

You can try this function

function isPalindrome(str){ 
    if(str.length < 2) return true;
    if(str[0] != str.slice(-1)) return false;
    return isPalindrome(str.slice(1,-1));
}

It uses recursion and its logic is as follows The empty and 1 character string are considered palindromes

if(str.length == 0 || str.length == 1) return true;

if the first and last characters are not the same the word is not a palindrome

if(str[0] != str.slice(-1)) return false;

if the first and last are the same continue searching in the remaining string

return isPalindrome(str.slice(1,-1));

var result = document.querySelector(".result");
var palindrome = "<span class='palindrome'>it is a palindrome</span>";
var notpalindrome = "<span class='notpalindrome'>it is NOT a palindrome</span>";

function isPalindrome(str){ 
    if(str.length == 0 || str.length == 1) return true;
    if(str[0] != str.slice(-1)) return false;
    return isPalindrome(str.slice(1,-1));
}

document.querySelector("input").addEventListener("keyup", function(){
  if(isPalindrome(this.value)){
    result.innerHTML = palindrome;
  } else {
    result.innerHTML = notpalindrome;
  }
})
.palindrome{color: green;}
.notpalindrome{color: red;}
<input type="text" />
<span class="result"></span>
eltonkamami
  • 5,134
  • 1
  • 22
  • 30
  • Thank you! I think I'm confused about the syntax and how to ID things - would "str" need to be the ID for the userInput, or would I have to define that as a variable, like: "var str = userInput"? – Robin D. Feb 20 '16 at 20:27
  • @RobinD. to use it in your code from a prompt for example you do `console.log(isPalindrome(prompt("Enter your word")))` – eltonkamami Feb 20 '16 at 20:28
  • Thanks! Really wondering why I wanted to take this class now. Thanks for your help! – Robin D. Feb 20 '16 at 20:33
  • @RobinD. here is an example with an input and feedback as they type the word http://codepen.io/anon/pen/ZQdGao?editors=0010 – eltonkamami Feb 20 '16 at 20:35
  • 1
    @Roberto thanks. just mentioned it so you dont get downvoted – eltonkamami Feb 20 '16 at 20:46
0

How are you collecting the user input? In just about every case, it will come into the program as a string (i.e. textbox, prompt), so you don't have to worry about converting it into one.

This code simply takes the word, breaks it into an array, reverses the array and then compares that reversal against the original word. It works for me:

function test(input){

   var originalData = input;
   var a = [];

   for(var i = 0; i < input.length; ++i){
      a.push(input.charAt(i));
   }

   a.reverse();
   return (a.join('') === originalData) ? true : false;
}


var word = document.getElementById("userWord");
alert(test(word)); 

See working version at: https://jsfiddle.net/6cett0bc/6/

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

The most basic version I can think of is to split the word into letters and check the first against the last, until you end up in the middle, where it doesn't matter if there is an odd amount of letters.

UPDATE I've tested the performance of various implementations and changed my array based answer to a pure string based solution. If you're curious, here are the performance benchmarks

The fastest solution (so far):

function palindrome(word) {
  var middle = Math.ceil(word.length / 2),  //  determine the middle
      i; //  prepare the iteration variable

  //  loop from 0 to middle
  for (i = 0; i <= middle; ++i) {
    //  check letter i against it counterpart on the opposite side
    //  of the word
    if (word[i] !== word[(word.length - 1) - i]) {
      //  it is not a palindrom
      return false;
    }
  }
  
  //  otherwise it is
  return true;
}

//  listen for clicks on the button and send the entered value to the palindrom function
document.querySelector('button').addEventListener('click', function(e) {
  //  obtain the input element
  var element = document.querySelector('input');

  //  add/remove the 'palindrom' CSS class to the input field, depending on
  //  the output of palindrome function
  if (palindrome(element.value)) {
    element.classList.add('palindrome');
  }
  else {
    element.classList.remove('palindrome');
  }
});
input {
  color: red;
}

input.palindrome {
  color: green;
}
<input name=check placeholder=palindrome><button>check</button>

The text turns green if you have entered a palindrome successfully, red (default) otherwise.

Rogier Spieker
  • 4,087
  • 2
  • 22
  • 25
  • Why not just put the letters into an array and then reverse the array and compare to original? See my code above. – Scott Marcus Feb 20 '16 at 19:58
  • thank you! I'll experiment with both of these. This class is WAY over my head. – Robin D. Feb 20 '16 at 20:00
  • That's also a valid option, surely faster to implement and easier to understand ;-) Maybe I overthought the issue, it just seemed more appropriate to have it a bit more subtle, then again.. I don't expect any palindrome books to arrive anytime soon, so maybe length is not an issue ;-) – Rogier Spieker Feb 20 '16 at 20:01