Search code examples
javascriptpalindrome

matching individual characters in a palindrome with javascript?


I can match to see if a string of numbers is or isn't a palindrome using a .reverse().join on the string, and get a true or false like:

var isPalindrome = function (string) {
  if (string == string.split('').reverse().join('')) {
    alert(string + ' is palindrome.');
  }
  else {
    alert(string + ' is not palindrome.');
  }
}

However, I need to figure out how many numbers match a palindrome pattern, not the whole word. For instance, if the user types in '112231' the return would be 2, '1234321' is 3, '4010220804' is 4, and so on.


Solution

  • I took the reversed and normal string and iterated over their indices since they should be the same length. I just created a counter and returned an alert if it wasn't a full palindrome.

     var isPalindrome = function(string) {
      let letters = string.split('');
      let reversed = Array.from(letters).reverse();
      if (string == reversed.join('')) {
        alert(string + ' is palindrome.');
        return true;
      } else {
        let matches = 0;
        for (let letter_index in letters) {
            if (letters[letter_index] === reversed[letter_index]) {
              matches++;
          }  
        }
        alert(matches);
      }
    }
    

     var isPalindrome = function(string) {
      let letters = string.split('');
      let reversed = Array.from(letters).reverse();
      if (string == reversed.join('')) {
        alert(string + ' is palindrome.');
        return true;
      } else {
        let matches = 0;
        for (let letter_index in letters) {
            if (letters[letter_index] === reversed[letter_index]) {
              matches++;
          }  
        }
        alert(matches);
        return matches;
      }
    }
    
    isPalindrome('tacocat');
    isPalindrome('tacocatat');
    isPalindrome('banana');
    isPalindrome('anana');