A palindrome is a word or phrase that reads the same way forward and backward. Identifying such unique strings has applications in data analysis, algorithms, and more. This tutorial will guide you on how to write a JavaScript program to determine whether a given string is a palindrome.



Examples of Palindromes:

Popular examples include 'radar,' 'madam,' 'pop,' and 'lol.'

How to Write a JavaScript Program for Palindrome String Check

Here's a concise, well-commented JavaScript code snippet that effectively identifies whether a given string is a palindrome or not.

Example:

function isPalindrome(str) {
    // Remove non-alphanumeric characters and convert to lowercase
    str = str.replace(/[^0-9a-z]/gi, '').toLowerCase();

    // Compare characters from the start and end of the string
    // and stop if a mismatch is found or the middle of the string is reached.
    for (let i = 0; i < str.length / 2; i++) {
        if (str[i] !== str[str.length - i - 1]) {
            return false;
        }
    }

    return true;
}

// Prompt the user for input
const string1 = prompt("Enter a string:");

// Output the result
if (isPalindrome(string1)) {
    console.log(`${string1} is a palindrome`);
} else {
    console.log(`${string1} is not a palindrome`);
}

Detailed Explanation:

The isPalindrome function first removes all non-alphanumeric characters and converts the string to lowercase. It then compares the characters of the string from the beginning and end and stops if a mismatch is found or the middle of the string is reached. If all of the characters match, then the string is a palindrome

Consider the string "radar". Its character comparison would be as follows:

---------------------------
index: 0 1 2 3 4

value: r a d a r
---------------------------

Palindrome String

To compare it with its own opposite, the following logic is used:

  1. The 0th character in the char array, string1, is the same as the 4th character in the same string.
  2. 1st character is the same as 3rd character.
  3. 2nd character is the same as 2nd character.
  4. . . . .
  5. ith character is the same as the 'length-i-1'th character.
  6. If any of the above conditions fails, the flag is set to true(1), implying that the string is not a palindrome.
  7. By default, the value of the flag is false(0). Hence, the string is a palindrome if all the conditions are satisfied.


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram