Algorithm


  1. Input:

    • Take the input string.
  2. Clean the String:

    • Remove non-alphanumeric characters from the string.
    • Convert the string to lowercase to ensure case-insensitivity.
  3. Reverse the String:

    • Reverse the cleaned string.
  4. Compare Strings:

    • Check if the cleaned string is equal to its reverse.
  5. Output:

    • If the cleaned string is equal to its reverse, then the input string is a palindrome.
    • Otherwise, it is not a palindrome.

 

Code Examples

#1 Code Example- Check Palindrome Using for Loop

Code - Javascript Programming

// program to check if the string is palindrome or not

function checkPalindrome(string) {

    // find the length of a string
    const len = string.length;

    // loop through half of the string
    for (let i = 0; i  <  len / 2; i++) {

        // check if first and last string are same
        if (string[i] !== string[len - 1 - i]) {
            return 'It is not a palindrome';
        }
    }
    return 'It is a palindrome';
}

// take input
const string = prompt('Enter a string: ');

// call the function
const value = checkPalindrome(string);

console.log(value);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: madam
It is a palindrome

#2 Code Example- Check Palindrome using built-in Functions

Code - Javascript Programming

// program to check if the string is palindrome or not

function checkPalindrome(string) {

    // convert string to an array
    const arrayValues = string.split('');

    // reverse the array values
    const reverseArrayValues = arrayValues.reverse();

    // convert array to string
    const reverseString = reverseArrayValues.join('');

    if(string == reverseString) {
        console.log('It is a palindrome');
    }
    else {
        console.log('It is not a palindrome');
    }
}

//take input
const string = prompt('Enter a string: ');

checkPalindrome(string);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: hello
It is not a palindrome
Advertisements

Demonstration


JavaScript Programing Example to Check Whether a String is Palindrome or Not-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way