JavaScript Code Snippet to Check if a String is a Palindrome

Programming languages or concepts

 JavaScript Code Snippet to Check if a String is a Palindrome



Introduction:

In web development, it's essential to write efficient code that performs various tasks quickly and accurately. One common task is checking whether a given string is a palindrome. In this article, we will provide you with a code snippet in JavaScript that accomplishes this task. Understanding this code snippet will not only improve your coding skills but also enhance your website's search engine optimization (SEO) by improving page performance.


Defining a Palindrome:

A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as it does forward. For example, "radar" and "madam" are palindromic words. To determine if a string is a palindrome, we need to compare it with its reverse form.


JavaScript Code Snippet:


Below is a JavaScript code snippet that checks whether a given string is a palindrome:



function isPalindrome(str) {

  // Remove all non-alphanumeric characters and convert the string to lowercase

  const formattedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');


  // Reverse the formatted string

  const reversedStr = formattedStr.split('').reverse().join('');


  // Compare the formatted string with its reverse

  return formattedStr === reversedStr;

}


// Example usage

const inputString = "A man, a plan, a canal, Panama!";

const result = isPalindrome(inputString);


console.log(result); // Output: true



Explanation:

1. The `isPalindrome` function takes a string as input.

2. The `formattedStr` variable removes all non-alphanumeric characters from the string and converts it to lowercase. This ensures that the comparison is case-insensitive and only considers alphanumeric characters.

3. The `reversedStr` variable reverses the `formattedStr` by splitting it into an array of characters, reversing the array, and joining the characters back into a string.

4. The function then compares `formattedStr` with `reversedStr` using the strict equality operator (`===`), returning `true` if they are equal, indicating that the string is a palindrome.

5. Finally, an example usage of the `isPalindrome` function is demonstrated by checking the input string `"A man, a plan, a canal, Panama!"`. The result is logged to the console.


Conclusion:

By utilizing the provided JavaScript code snippet, you can easily check if a given string is a palindrome. This code snippet removes non-alphanumeric characters, converts the string to lowercase, and compares it with its reverse to determine palindromic properties. Understanding and implementing such efficient code enhances your web development skills and contributes to improved SEO by ensuring optimal page performance.

close