Check If String is a Palindrome in JavaScript



In the given problem statement we have to find that the string is a palindrome and the string should also have punctuation and write code with the help of Javascript functionalities. Here we will learn two methods to determine if a string is a palindrome in JavaScript while handling punctuation and spaces effectively.

What is a Palindrome?

A palindrome is not limited to single words like "radar" or "level"; it can include phrases or sequences like "Madam, in Eden, I'm Adam." We need to ignore punctuation, spaces, and case differences to ensure accurate palindrome checks.  

Using JavaScript String and Array Methods 

One of the simplest approaches to check for palindromes is by leveraging JavaScript's built-in string and array methods. Normalize the string by removing all non-alphanumeric characters and converting it to lowercase. Reverse the cleaned string. Compare the reversed string with the cleaned string. 

  • The JavaScript toLowerCase() method creates a new string with all characters converted to lowercase. It leaves the original string unchanged and returns the modified version.
  • The Array.reverse() method in JavaScript reverses the order of elements in an array, making the first element last and the last element first. It modifies the original array.
  • The join() method combines all elements of an array into a single string. It doesn't alter the original array but returns the resulting string.

Algorithm

Step 1: We have to find out if the given string is a palindrome or not. So to do this task we will create a function called isPalindrome and in this function, we will pass a parameter of string as str. So for this str, we will check the palindrome condition.

Step 2: After the creation of the function we will convert the given string into lowercase with the help of the toLowerCase() method and then we will assign it to the new variable called lowerCaseStr.

const lowerCaseStr = str.toLowerCase();

Step 3: Now we have converted the string into lowercase, it is time to remove the spaces and punctuations from the given string with the help of regular expressions and string manipulation methods. After this, we will assign it to another variable called modifiedStr.

const modifiedStr = lowerCaseStr.replace(/[\W_]/g, '');

Step 4: In this step, we will reverse the given string with the help of split, reverse and join methods and then we will assign it to a new variable called reversedStr.

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

Step 5: We have already converted the string to lowercase and reversed the given string. We will compare the updated string with the reversed string using the === operator. If they are equal we will return true; otherwise, we will return false.

return modifiedStr === reversedStr;

Example 

Below is an example to find if the string is a palindrome using JavaScript String and Array Methods ?

// Function to check for Palindrome
function isPalindrome(str) {
   const lowerCaseStr = str.toLowerCase();
   const modifiedStr = lowerCaseStr.replace(/[\W_]/g, '');
   const reversedStr = modifiedStr.split('').reverse().join('');

   return modifiedStr === reversedStr;
}
const inputString = "A man, a plan, a canal, Panama!";
console.log(isPalindrome(inputString));

Output

true

Using Two-Pointer Technique

For a more efficient solution, especially for large strings, the two-pointer technique is a great option. Instead of reversing the string, this method compares characters from the beginning and end simultaneously.
one pointer starting at the beginning ?

let left = 0;

The other pointer at the end of the string ?

let right = cleanedStr.length - 1;

Move the pointers inward, checking for character equality ?

while (left < right) {

left++;
right--;
}

Example

Below is an example to find if the string is a palindrome using the Two-Pointer Technique ?

function isPalindromeTwoPointer(str) { 
    // Remove punctuation, spaces, and convert to lowercase
    const cleanedStr = str.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
    let left = 0;
    let right = cleanedStr.length - 1;
    while (left < right) {
        if (cleanedStr[left] !== cleanedStr[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// Example usage
console.log(isPalindromeTwoPointer("A man, a plan, a canal, Panama")); 
console.log(isPalindromeTwoPointer("Not a palindrome!")); 

Output

true
false

Complexity

The time complexity for finding whether the given input string is palindrome or not is O(n), in which n is the size of the given input string. As we have used regular expression and string manipulation techniques which require linear time and also modification for the string it also takes linear time.

Conclusion

The string manipulation approach is straightforward and ideal for small inputs, while the two-pointer technique offers better efficiency for larger strings. Both methods handle punctuation, spaces, and case differences, ensuring reliable results across diverse scenarios. These techniques provide robust solutions for integrating palindrome checks into JavaScript applications.

Updated on: 2024-12-13T13:54:15+05:30

701 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements