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

I want to create a palindrome check in javascript. All non-letter characters must be removed, so a phrase like "Man, plan, channel. 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;
  }
}
Run codeHide result

Now, where is the error in the above lines?

The code works on some examples. But, for example, "Man, plan, channel, Panama" and "never strange or even" do not return a lie, which means that something must be a mistake.

+4
source share
5 answers

You need to provide a global match flag for your regular expression:

/[^a-zA-Z]+/g
            ^
+5

. replace() , . . regEx :

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;
  }
}

.

+1

From the above example, it seems to me that the code does not work for spaces between letters. (There may be other scenarios)

I changed this line:

str = str.replace(/[^a-zA-Z]+/,"").toLowerCase();

For this:

str = str.toLowerCase().replace(/[^a-z]/g,"");
+1
source

change this line:

str = str.replace(/[^a-zA-Z]+/,"").toLowerCase();

:

str = str.toLowerCase().replace(/[^a-z0123456789]+/g,""); 
+1
source

This regex should work for your code.

/[^1-9a-zA-Z]+/g

-1
source

Source: https://habr.com/ru/post/1605921/


All Articles