How to check if a string is a palindrome with JavaScript?

Sometimes, we want to check if a string is a palindrome with JavaScript.

In this article, we’ll look at how to check if a string is a palindrome with JavaScript.

How to check if a string is a palindrome with JavaScript?

To check if a string is a palindrome with JavaScript, we can use the JavaScript string’s split and JavaScript array’s reverse and join methods.

For instance, we write:

const isPalindrome = (s) => {
  return s === s.split("").reverse().join("");
}

console.log(isPalindrome('foobar'))
console.log(isPalindrome('abba'))

to create the isPalindrom function to check the string s is the same as the original after we reversed the letters in it.

We reverse s by splitting it with split with an empty string to return an array of characters in the string.

Then we call reverse to reverse the array.

And we call join with an empty string to join the characters back into a string.

Finally, we return s compared with the reversed version of s with ===.

Therefore, from the console log, we should see false and then true logged respectively.

Conclusion

To check if a string is a palindrome with JavaScript, we can use the JavaScript string’s split and JavaScript array’s reverse and join methods.