blue       earthtones
Detecting Palindromes

"Palindrome Detection" is a common exercise in computer science classes and programming job interviews. Palindromes are simply text strings which read the same in both forward and reverse directions. Since palindromes can arise not only as individual words or numbers, but also in phrases and entire sentences, the solution involves converting case, stripping out punctuation and spaces, and then comparing the surviving text to its reverse.


Definition of PALINDROME

: a word, verse, or sentence (as "Able was I ere I saw Elba") or a number (as 1881) that reads the same backward or forward

Origin of PALINDROME

Greek palindromos: "running back again", from palin: back, again + dramein: to run; akin to Greek "polos": axis, and pole.

First Known Use: circa 1629

source: Merriam-Webster

The Algorithm

Detecting palindromes is a simple algorithm:

  1. reduce the source text to lower case;
  2. strip punctuation and spaces;
  3. reverse the purified result and compare it to the original.

The JavaScript Code:

function palindrome(theStringId) {
    var testCase = document.getElementById(theStringId).value.toLowerCase().match(/([a-z]|[0-9])/g);
    var cleaned = testCase.join(''); // stringify
    var mirror = testCase.reverse().join(''); // reverse and stringify
    var result = (cleaned === mirror) ? 'Yes' : 'No';
    }
				

Test Cases: Palindrome Detection

Test Case: