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

▼魔方 西西 提交于 2019-12-01 06:48:13

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

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

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.

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,"");

change this line:

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

to this:

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

This regex should work for your code.

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

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