find out if string is palyndrome4 in javascript

To check if a string is a palindrome, you can compare the characters from both ends of the string. If they are equal, continue comparing until the middle of the string has been reached.

Here is a JavaScript function that checks for palindromes:

index.tsx
function isPalindrome(str) {
  // Remove non-alphanumeric characters and convert to lowercase
  str = str.replace(/[^0-9a-z]/gi, '').toLowerCase();
  
  // Reverse the string
  let reversedStr = str.split('').reverse().join('');
  
  // Compare the original string with the reversed string
  return str === reversedStr;
}
322 chars
11 lines

This function first removes any non-alphanumeric characters and converts the string to lowercase. It then reverses the string using the reverse() method, and joins the characters back together using the join() method. Finally, it compares the original string with the reversed string using the strict equality operator.

You can use this function like this:

index.tsx
let str1 = 'racecar';
let str2 = 'hello';
console.log(isPalindrome(str1)); // true
console.log(isPalindrome(str2)); // false
125 chars
5 lines

related categories

gistlibby LogSnag