I'm struck at 'Check for pallindromes'

Here is my code -
[code]
function palindrome(str) {
// Good luck!
var str1 = str.replace(/\W/g,’’);
var str2 = str1.toLowerCase();
var pal = true;
for(var i = 0; i < str2.length-1; i++){
var j = str2.length - i -1;
if(str2[i] != str2[j]){

          pal = false;
        }
  }
  return pal;
}

[/code]
Only the testcases - palindrome("_eye") and palindrome("0_0 (: /-\ :) 0-0") are not passing. I’m still trying to figure out what’s wrong with the code, any help is appreciated.

Here is an awesome site: http://www.regexr.com/

Input your regex and in the text field input string from your test cases and see the result.

2 Likes

Thanks for the link! :slight_smile:
So the problem basically is the regex i have given doesn’t detect underscore. I gave a separate replace statement for _ and completed.

Congratulations!

To avoid similar problems, I would recommend you to use this regex:

/[^A-Za-z\d]/g

You can also make .toLowerCase() first and then use this:

/[^a-z\d]/g

It explicitly checks if character is not (^) lowercase letter or digit.

Also you can chain methods in Javascript, like this:

var str2 = str.toLowerCase().replace(/[^a-z\d]/g, '');
1 Like

A post was split to a new topic: Check for Palindromes: Always returns true