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

耗尽温柔 提交于 2019-12-30 10:32:15

问题


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.


回答1:


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

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



回答2:


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.




回答3:


From the example given, it seems to me that the code doesn't work for spaces in between the letters. (There may be other scenarios as well)

I have changed this line :

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

To this :

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



回答4:


change this line:

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

to this:

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



回答5:


This regex should work for your code.

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



来源:https://stackoverflow.com/questions/32395229/palindrome-checker-in-javascript-dont-know-how-to-debug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!