how do you determine if a string is a palindrome in javascript

To determine if a string is a palindrome in JavaScript, you can compare the first and last character and progressively compare the characters until the middle of the string is reached.

Here's an example code snippet that uses this approach:

index.tsx
function isPalindrome(str){
  // remove non-alphanumeric characters and convert to lowercase
  str = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
  
  // compare first and last characters, second and second to last characters, and so on
  for(let i = 0, len = str.length; i < len / 2; i++){
    if(str[i] !== str[len - 1 - i]){
       return false; // characters do not match
    }
  }
  return true; // string is a palindrome
}

// example usage
console.log(isPalindrome("A man, a plan, a canal, Panama!")); // true
console.log(isPalindrome("Hello world")); // false
571 chars
17 lines

related categories

gistlibby LogSnag