OneBite.Dev - Coding blog in a bite size

How to check if string is Palindrome in Javascript

Checking if a string is a palindrome (same when reversed) in javascript. Also handling white space chars.

Here is how to check if a given string is a palindrome (same when reversed) in Javascript

function isPalindrome(str) {
  // We remove all non-alphanumeric characters, convert to lower case and trim spaces
  str = str.replace(/[\W_]/g, '').toLowerCase();

  // We compare the original string with its reverse
  return (str == str.split('').reverse().join(''));
}

console.log(isPalindrome("A man, a plan, a canal: Panama"));  // Should print: true
console.log(isPalindrome("not a palindrome"));  // Should print: false

Idea: turn in intro array, reverse the array and join it back. Then compare with original

What is a palindrome

A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. In other words, it’s symmetrical along its center.

Examples of palindromic words include “radar”, “level”, “rotor”, “madam”, and “racecar”. An example of a palindromic phrase could be “Able was I ere I saw Elba”. This phrase remains the same when read backward if you ignore spaces, punctuation, and capitalization.

In the context of programming, a common problem is to determine whether a given string is a palindrome or not. This is typically done by comparing the string to its reverse and checking if they are equal.

← Check array only contains...
How to find the maximum c... →
javascript