JavaScript - Find if string is a palindrome (Check for punctuation)

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that returns true if a given string is a palindrome. Otherwise, returns false.

These are the conditions we have to keep in mind while validating the string −

  • We have to remove punctuation and turn everything lower case in order to check for palindromes.

  • We have to make it case insensitive, such as "racecar", "RaceCar", and "race CAR" among others.

Example

Following is the code −

const str = 'dr. awkward';
const isPalindrome = (str = '') => {
   const regex = /[^A-Za-z0-9]/g;
   str = str.toLowerCase().replace(regex, '');
   let len = str.length;
   for (let i = 0; i < len/2; i++) {
      if (str[i] !== str[len - 1 - i]) {
         return false;
      };
   };
   return true;
};
console.log(isPalindrome(str));

Output

Following is the output on console −

true
raja
Published on 10-Dec-2020 12:24:18
Advertisements