Function to Check Palindrome

JavaScript

Function to check if a given string is a palindrome:

You can create a JavaScript function to check if a given string is a palindrome by comparing characters from both ends of the string. Here's a simple implementation:

js Copy Code
function isPalindrome(str) {
    // Remove non-alphanumeric characters and convert to lowercase
    const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
    
    // Compare characters from start and end simultaneously
    for (let i = 0; i < cleanStr.length / 2; i++) {
        if (cleanStr[i] !== cleanStr[cleanStr.length - 1 - i]) {
            return false; // If characters don't match, it's not a palindrome
        }
    }
    
    return true; // If all characters match, it's a palindrome
}

// Example usage:
console.log(isPalindrome("A man, a plan, a canal, Panama")); // Output: true
console.log(isPalindrome("racecar")); // Output: true
console.log(isPalindrome("hello")); // Output: false
Output:
true
true
false

This function first removes non-alphanumeric characters and converts the string to lowercase to ensure a case-insensitive comparison. Then, it iterates through the string, comparing characters from the start and end until the middle is reached. If any characters don't match, it returns 'false'; otherwise, it returns 'true'.

Algorithm: Palindrome Sequences in Mathematical Terms

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.