0

My question has two parts. I'm trying to check whether a date is a palindrome or not. In the following code, I continuously get the result of "Not a palindrome" even if the string is in fact a palindrome.

function isPalindrome(str){
    var rev = str.reverse;
    if(str === rev){
        console.log("This is a palindrome.");
    }
    else{
        console.log("Not a palindrome");
    }
}

isPalindrome("2002");

The second part to my question is: if I wanted the function to take two arguments function isPalindrome(start_date, end_date)and have it check the dates between for palindrome years and then return those years chronologically, how do I do that? I'm not asking for anyone to actually do it for me. I'm just asking for an explanation on how to accomplish it.

Thanks in advance.

ilgaar
  • 804
  • 1
  • 12
  • 31
  • @bobdye well that's not helpful at all –  Feb 24 '15 at 22:38
  • There's no native reverse function on strings in javascript. Where is this `reverse` defined? Also, you'd need to call it with parentheses if you want it to reverse the string. `var reversed = mystr.reverse();` – Chris Farmer Feb 24 '15 at 22:48

3 Answers3

0

It could be something with the reverse function you are using. You could output the value of rev to see what's going one.

I would suggest you use this: How do you reverse a string in place in JavaScript?

Community
  • 1
  • 1
sixer24
  • 26
  • 1
  • 4
  • I didn't know that question existed. It answered my question, thank you. –  Feb 25 '15 at 13:57
0

I'm not familiar with any string reverse() function in anybody's native javascript implementation. But here's something I wrote a while back that does the palindrome thing, fwiw:

String.prototype.reverse = function (){
    //Another way to reverse a string is to use Array's reverse:
    //  "this.split('').reverse().join('')"; 
    //but that's boring, and recursion is fun!
    if (this.length < 2) { return this.toString() };
    return this.slice(-1) + this.slice(0,-1).reverse();
}
String.prototype.is_palindrome = function (){
    return this.toString() === this.reverse();
}

This checks whether a string is a palindrome.

As for the second part of your question, I'm not sure how to do that off the top of my head. I would start by seeing what's natively available via javascript's Date object. Check MDN. You would only have to handle the years, so I'd just figure out the year range first and iterate over that, checking for palindromes along the way.

Jon Carter
  • 2,836
  • 1
  • 20
  • 26
-1

Are you stripping out the non-numeric characters first?

var strippedDate = str.replace(/[^\d]/g, "");
return strippedDate == strippedDate.reverse();
Paul Rowe
  • 778
  • 3
  • 10