JavaScript Algorithms and Data Structures Projects - Palindrome Checker

Tell us what’s happening:
Describe your issue in detail here.
I want if str is a string or string with symbols to return false
Your code so far

function palindrome(str) {
// to reverse the words and sentences  
  let rev = str.split("").reverse().join("");
// if the  word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.
  let non = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
if(str == rev) { 
    return true;
  }else if(str = non) {
    return true;
  }
}

palindrome("eye");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/113.0

Challenge: JavaScript Algorithms and Data Structures Projects - Palindrome Checker

Link to the challenge:

2 Likes

Why don’t you strip off the punctuation and lowercase the string before you reverse it?
Then all you need do is a straight comparison of the string and its reverse.

1 Like

Can you explain more

1 Like

This line of code gives you str with no spaces or punctuation:

let non = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();

This line of code reverses str:

let rev = str.split("").reverse().join("");

So why not put the lines in this order but, instead of reversing str, reverse non?
Then you can simply compare them. If they’re the same, that means that str is palindromic.

function palindrome(str) {
// to reverse the words and sentences  
  let rev = str.split("").reverse().join("");
// if the  word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.
  let non = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
if(str = non) { 
    return true;
  }else if(str == rev) {
    return true;
  }
}
// like this
palindrome("eye");

Explain to us in English what your algorithm does.

You haven’t really changed anything.
As @bbsmooth says, can you explain what each line of your code does?
If you can do that, then you should be able to work out how to make your logic work for you.

I did this

function palindrome(str) {
// if the  word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.
   str = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
if(str === str.split("").reverse().join("")) { 
    return true;
  }else {
    return false;
}
}
palindrome("eye");

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.