Algorithm 101: 6 Ways to Check if a Word is a Palindrome
NJOKU SAMSON EBERE
Posted on March 5, 2020
If you followed my Algorithm 101 first episode, then this will be very easy. Here, the main objective is to reverse a given word and check if it still matches the given word.
wordPalindrome("Racecar"); // true
wordPalindrome("Race car"); // false
In how many ways can you achieve this? I have 6 ways to Check if a given Word is a Palindrome. I know you will like to check them out.
This article will focus on word palindrome
only. In a future episode, we will be looking at sentence palindrome.
Prerequisite
This article assumes that you have basic understanding of javascript's string and array methods.
Let's Check if a Word is a Palindrome using:
- toLowerCase(), split(), reverse(), join(), if...statement;
function wordPalindrome(word) {
let lowerCasedWord = word.toLowerCase();
let newWord = lowerCasedWord
.split("")
.reverse()
.join("");
if (newWord === lowerCasedWord) {
return true;
}
return false;
}
- toLowerCase(), spread operator, reverse(), join(), if...statement;
function wordPalindrome(word) {
let lowerCasedWord = word.toLowerCase();
let newWord = [...lowerCasedWord].reverse().join("");
if (newWord === lowerCasedWord) {
return true;
}
return false;
}
- toLowerCase(), spread operator, if...statement
function wordPalindrome(word) {
let lowerCasedWord = word.toLowerCase();
let newWord = [...lowerCasedWord].reduce((total, acc) => acc + total);
if (newWord === lowerCasedWord) {
return true;
}
return false;
}
- toLowerCase(), for...loop, join(), if...statement;
function wordPalindrome(word) {
let lowerCasedWord = word.toLowerCase();
let newWord = [];
for (let i = lowerCasedWord.length; i >= 0; i--) {
newWord.push(lowerCasedWord[i]);
}
if (newWord.join("") === lowerCasedWord) {
return true;
}
return false;
}
- toLowerCase(), for...of...loop, if...statement;
function wordPalindrome(word) {
let lowerCasedWord = word.toLowerCase();
let newWord = "";
for (char of lowerCasedWord) {
newWord = char + newWord;
}
if (newWord === lowerCasedWord) {
return true;
}
return false;
}
- toLowerCase(), for...in...loop, if...statement;
function wordPalindrome(word) {
let lowerCasedWord = word.toLowerCase();
let newWord = "";
for (char in lowerCasedWord) {
newWord = lowerCasedWord[char] + newWord;
}
if (newWord === lowerCasedWord) {
return true;
}
return false;
}
Conclusion
There are many ways to solve problems programmatically. You are only limited by your imagination. I will love to know other ways you solved yours in the comment section.
If you have questions, comments or suggestions, please drop them in the comment section.
You can also follow and message me on social media platforms.
Thank You For Your Time.
Posted on March 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.