Check if Strings are Palindromes with JavaScript
A palindrome is a word, phrase, or sequence that reads the same backward as forward. If you’ve learned how to reverse a string (if you haven’t, we wrote an article involving it here), then a straight-forward, easy solution to this problem might come instantly to mind. You might reverse the string, compare it to the original, unchanged value, and there you have it, a solution.
This works, but let’s explore another solution. It’s always better to know multiple ways to solve something.
Directions
- Given a string, return true if the string is a palindrome or false if it is not.
- Palindromes are strings that form the same word if it is reversed.
Examples
palindrome("racecar") === true
palindrome("abcdefg") === false
The Solution From our Description
function palindrome(str) {
return str.split("").reverse().join("") === str;
}
palindrome("racecar");
// Output: true
That’s it. Very simple indeed. Let’s explore another solution:
function palindrome(str) {
return str.split("").every((char, i) => {
return char === str[str.length - i - 1];
});
}
palindrome("Hello");
In the above solution, we used the array .every()
method, which checks whether all elements (char
) pass the tests provided by the function. (You might be wondering how we’re using an array method. Remember that .split()
converts a string to an array.)
The code basically says ‘for every character’, return char
equal to str minus i minus 1
. Here, char
is the regular ordered string (i.e. 'H', 'e', 'l', 'l', 'o'
), while the str - i - 1
will be the reverse (i.e. 'o', 'l', 'l', 'e', 'H'
), so as you can imagine, these two values will be compared, and thus we will get our true
or false
value.
That’s it!
Don’t forget to check out these three simple algorithms, and let us know what you think in the Disqus comments below!
Related Posts
Finding Free and Discounted Programming Books
As an avid reader, I’m always looking for places to find my next book. If they’re free, even better. Although it’s not always so easy finding them, there are plenty available online.
Read moreGetting Started with Google Cloud
In this article, we’re going to be taking a first look at Google Cloud, a leading player in the world of cloud computing, offers services and tools designed to drive innovation and ease operations.
Read moreThe Great JavaScript Debate: To Semicolon or Not?
Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.
Read more