Check for Palindromes - Refining

Hi all,

So this isn’t so much problem help, more refining help. I can’t help but feel that the solution I created is the long way around of doing things. It works fine, but I don’t have much experience outside of freeCodeCamp and I wanted to ask for help refining this code. Thanks for any help in advance!


Your code so far

  // Good luck!
var eStr = []; //edited string
var rStr = []; //reversed string
var lStr = ""; //lowercase string
var crap = ["_"," ",":","/","\\",":","-",",",".","\(","\)"];
lStr = str.toLowerCase();
  for (i = 0; i < crap.length; i++) {
    var reg = new RegExp("\\" + crap[i],"g");
    lStr = lStr.replace(reg, "");

eStr = lStr.split('');  
rStr = eStr;
eStr = lStr.split('');  
  for (i = 0; i < eStr.length; i++) {
    if (eStr[i] === rStr[i]) {
    } else {
    return false;  
  return true;


Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36.

Link to the challenge:

Haiiiiyo, some suggestions:

  • You may want to use replace() and regex expressions to do the filtering—not least because there are certainly many more non-alphanumeric characters than those!
  • Making the reserved string using join() lets you get rid of the for loop. I’m not sure whether that is more performant or not, but it certainly makes the code much cleaner and is probably at least not slower

Here is an example:

function palindrome(str) {
  const filteredStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
  const reversedFilteredStr = filteredStr.split('').reverse().join('');
  const isPalindrome = filteredStr === reversedFilteredStr;
  return isPalindrome;

The number of lines can be cut down further as below, but I personally think that the extra lines of code makes it much easier for others to follow:

function palindrome(str) {
  const filteredStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
  return filteredStr === filteredStr.split('').reverse().join('');

Oh my, two lines, that’s amazing. Thank you.
There’s a lot I have learnt from this :slight_smile:

I blurred out your solution, since it is a complete solution and we don’t want to ruin it for someone who was looking for help but did not want to see complete solution yet.

Thank you :slight_smile: