How to check if a string is palindrome - JS

Mo Ibra

Mo Ibra

Dec 23, 2022

In this article we will learn how check if a string is palindrome.

It is very common check if a string is palindrome in JavaScript.


Problem:

We must know the problem first before we know the solution.

We have a problem, which is that we want to know if the string is palindrome or not.

The palindrome is if we reverse the word, it will be the same as before the reverse.

Example

"mom"   // palindrome => true
"civic" // palindrome => true
"Madam" // Yo, Banana Boy!
"Yo, Banana Boy!" // palindrome => true

Solution?

Now you understand the problem, but how will you solve that problem?

The solution is simple, as long as the string is the same after the reverse, we will reverse the string and put it in a new variable and then compare them.

The solution will be as follows:

  • Reverse the string and define it in new variable.
  • Compare two strings.
  • If strings is same return true.
  • If strings is not same return false.

Check if a string is palindrome solution:

function isPalindrome(str) {
    
    // 1. Reverse the string
    let reversedStr = str.split('').reverse().join('');

    // 2. Compare two strings
    if (str === reversedStr) {
        // 3. Return true if same
        return true;
    }

    // 4. Otherwise return false
    return false;
}

console.log(isPalindrome("mom"));
console.log(isPalindrome("mama"));

Output

true
false

Now let's do some tests

console.log(isPalindrome("Madam"));
console.log(isPalindrome("Yo Banana Boy"));

Output

false
false

OH!! why false?

Well now why was the output false?

Because he saw the two strings differently because the capital letters.

To solve this problem, we must make all letters lowercase

function isPalindrome(str) {

    let reversedStr = str.split('').reverse().join('');

    // Fix <toLowerCase() func>
    if (str.toLowerCase() === reversedStr.toLowerCase()) {
        return true;
    }

    return false;
}

Now if we do same tests.

console.log(isPalindrome("Madam"));
console.log(isPalindrome("Yo Banana Boy"));

Output

true
false

The first problem has been fixed, but the second is still there.

We need to remove all whitespaces from a string, and we will fix it with regular exp.

function isPalindrome(str) {

    // Remove all whitespaces from string
    str = str.replace(/ /g,'');

    let reversedStr = str.split('').reverse().join('').replace(/ /g,'');

    if (str.toLowerCase() === reversedStr.toLowerCase()) {
        return true;
    }

    return false;
}

Now if we do same tests.

console.log(isPalindrome("Madam"));
console.log(isPalindrome("Yo Banana Boy"));

Output

true
true

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: