Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Palindrome Checker in JavaScript - don't know how to debug

I want to build a palindrome checker in javascript. All non-letter characters should be removed, so that a phrase like "A man, a plan, a canal. Panama" can also be a palindrome.

function reverse(str) {
  return str.split("").reverse().join("");
}


function palindrome(str) {
  str = str.replace(/[^a-zA-Z]+/,"").toLowerCase();
  if(str == reverse(str)) {
    return true;
  }
  else {
    return false;
  }
}

Now, where is the mistake in the above lines?

The code works on some examples. But for instance "A man, a plan, a canal. Panama" and "never odd or even" return false, meaning somewhere has to be a mistake.

like image 952
k_rad Avatar asked Mar 15 '23 21:03

k_rad


2 Answers

You need to provide the global match flag to your regex:

/[^a-zA-Z]+/g
            ^
like image 64
sp00m Avatar answered Mar 25 '23 04:03

sp00m


This is a common misconception. The replace() method does not replace all instances of what you want to replace in a string. It simply replaces the first instance and stops. If you refactor your regEx like this:

function reverse(str) {
  return str.split("").reverse().join("");
}


function palindrome(str) {
    var find = "[^a-zA-Z]";
    var regEx = new RegExp(find, 'g');
  str = str.replace(regEx,"").toLowerCase();
  if(str == reverse(str)) {
    return true;
  }
  else {
    return false;
  }
}

That will work.

like image 39
James Walters Avatar answered Mar 25 '23 03:03

James Walters