# freeCodeCamp Challenge Guide: Palindrome Checker

We were supposed to ignore the digits and special characters

1 Like

function palindrome(str) {

var newstr1 = str.replace(/[\W_]/g,’’).toLowerCase();
var newstr2 = newstr1.toLowerCase().split(’’).reverse().join(’’);

return newstr1===newstr2;

/*
[ and ] are the start and end of a character set.
\W means “non-word”, as opposed to \w which will match a word.
_ is the “_” character.
/ mark the beginning and end of a regular expression.
g means it’s a global search.
*/
}

palindrome(“A man, a plan, a canal. Panama”);

1 Like

RegEx aka Extraterrestrial hieroglyphics…

function palindrome(str) {
// Good luck!
var noSpaces = str.replace(/(|)|.|\s|_|-|,|/gi, “”).toLowerCase();
var reverseMe = noSpaces.split("").reverse().join("");

if (noSpaces !== reverseMe) {
return false;
}
return true;
}

palindrome(“0_0 (: /-\ 0-0”);

My code is also very clean, and it works perfectly.

function palindrome(str) {
loweredstr=str.toLowerCase();//Make the string to lower case

`````` arr=loweredstr.match(/[a-z0-9]/g);
cleanstr=arr.join("");
arr.reverse();
reversecleanstr=arr.join("");
return cleanstr==reversecleanstr;
``````

}

I need some explanation concerning RegExp.

According to the following example
`str.replace(/[\W_]/g, '').toLowerCase();`

However, i did note found any mention about the use of the following characters: _ [ and ]

Can somebody explains to me their usage?

Thank you.

Hm I came here after I solved my solution, but my answer looks like nothing everyone else posted

Granted its not the most optimal solution in terms of how fast it calculates the answer (supposedly `reverse()` takes a lot of computational power, but oh well heres my working OC answer

I was quite surprised at people using `forloops` and `while loops` as well though. I didn’t even use any

``````function palindrome(str) {
//Clean up string
var re = /[^a-z0-9]/gi;
str=str.toLowerCase();
str=str.replace(re,'');
console.log(str);

//Reverse string and check
var pstr = str.split('').reverse().join('');
if (pstr === str){
return true;
}
return false;
}

palindrome("__Eye");
``````

brief explanation of how code works:

The first part cleans up the code. We don’t want nonalpha-numeric characters, and the recommendation was to use the `string.prototype.replace()` method as one of the suggested things to look up

The `replace` method takes in two inputs, where the first input can be a regex expression, according to the MDN. Last input I just used `''` to delete matching statements.

I had almost no conceptual knowledge of how regex works for the longest time (asides from the 4 lessons on freecodeCamp) so I watched this first video on derek banas regex tutorial 1, which I found very helpful

This gave me enough of an overview so I then looked into online RegEx tools to streamline my testing:

After checking many recommendation on online regex tools and recommendations from reddit/stackoverflow https://regex101.com/ was very robust with many useful library cheat sheet quick references at the bottom right

Being lazy in actually testing all the inputs, I decided I would just copy paste the test-case scenarios at the bottomleft on the freecodecamp problem and paste it right in and test the regex statements

Instead of actually checking for things like commas, underscores, punctuation marks, etc I thought it would be significantly simpler to just check for alphanumeric characters and then do the reverse of it. Since there’s so many operators (including unicode chars) like !@#\$%↑<,→↓_|{}();’./ that could be in the palindrome statements.

This wasn’t the case, but you know it could’ve been something to test for too.

Anyways, this is what my regex expression does on the ` var re = /[^a-z0-9]/gi;`, which is the most difficult statement to understand

Basically,

• `g` means global which checks if there’s more than 1 special char in the string value.
• `i` is for case sensitivity, it wasn’t necessary to have this actually
• `[a-z0-9]` means that it searches for all lower case chars a,b,c,d,e,f…x,y,z and 0,1,2…7,8,9 chars. Which is all alphanumeric values selected
• `[^a-z0-9]` inverses the selection, so any NONALPHA numeric characters are selected

Also, the other long statement `var pstr = str.split('').reverse().join('');` . That’s the official answer from the previous solution you can find it here : freeCodeCamp Challenge Guide: Reverse a String . I used that as a template

### Extra notes about debugging

I used repl.it to do all the testing per FCC recommendations

https://repl.it/JVCf/25

The built in console with FreeCodeCamp is lacking and doesn’t allow `console.log()` statements to make it easier to debug problems with your code. Repl.it requires absolutely no setup, super intuitive, and is probably the most uncomplicated way of having testing javascript that I’ve found (tried Chrome tools, Visual studio code, JSbin, Atom.io, cloud9 ide)

Anyways I suggest using repl.it instead of the freecodecamp debugger

7 Likes

Intermediate solution needs to have `;` on it for clarity.

I edited the wiki to reflect the correct statements

``````//this solution performs at minimum 7x better, at maximum infinitely better.
//read the explanation for the reason why. I just failed this in an interview.
function palindrome(str) {
//assign a front and a back pointer
let front = 0;
let back = str.length - 1;

//back and front pointers won't always meet in the middle, so use (back > front)
while (back > front) {
//increments front pointer if current character doesn't meet criteria
while ( str[front].match(/[\W_]/) ) {
front++;
continue;
}
//decrements back pointer if current character doesn't meet criteria
while ( str[back].match(/[\W_]/) ) {
back--;
continue;
}
//finally does the comparison on the current character
if ( str[front].toLowerCase() !== str[back].toLowerCase() ) return false;
front++;
back--;
}

//if the whole string has been compared without returning false, it's a palindrome!
return true;

}
palindrome("Eye");
``````
1 Like

function palindrome(str) {
str = str.toLowerCase();
str= str.replace(new RegExp("[^a-z0-9]",“g”),"");
if(str.length<=1){
return true;
}
if((str.charAt(0)) != (str.charAt(str.length-1))){
return false;
}else{
return palindrome(str.substr(1,str.length-2));
}
}

console.log(palindrome(“never odd or even”));

My Solution. I obviously had some fun making my regEx expression variable.

``````function palindrome(str) {

var letters = [];
var rword = "";

for (var i = 0; i < str.length; i++) {
letters.push(str[i]);
}

for (var i = 0; i < str.length; i++) {
rword += letters.pop();
}

var regEx = /_|[\. ,:-\s\/\/\)/]+/g;

if (rword.replace(regEx,"").toLowerCase() === str.replace(regEx,"").toLowerCase()) {
return true;
}

return false;
}

palindrome("0_0 (: /-\ :) 0-0");``````

Is there anything inefficient from my code?

function palindrome(str) {
// Clean up string input and lower case the string
var reg = str.replace(/[\W_]/g, ‘’).toLowerCase();
var back = reg.length-1; //get index of last position
var truth = true;

for(k=0; k <= back/2; k++){ //palindromes will be even
if(reg[k] !== reg[back-k]){
truth = false;
}
}
return truth;
}

Is there a reason why advanced solution is slowest on this test?
jsperf - palindrome

Can someone read through my code and tell me if the method is acceptable and if there is some tweaks you would add to make it more readable/shorter/perform better :

function palindrome(str) {
// delete all non-alphanumeric chars and write into lower cases
var normalize = str.replace(/[\W_]/g, “”).toLowerCase();
// split characters into an array and reverse the order
var intoArray = [];
intoArray = normalize.split("");
var reversed = intoArray.reverse();
// put the reversed characters back into a string
var reversedString = reversed.join("");

if (normalize !== reversedString) {
return false;
}
return true;
}

The code I came up with is similar to the basic solution:

```function palindrome(str) {
var array = str.replace(/[\W_]/g, '').toLowerCase().split('');
return array.join('') === array.reverse().join('');
}```

However, what I had at first was:

`return array === array.reverse();`

which kept on returning true even when the string was not a palindrome, and I still don’t understand the reason for that. Can anyone help me understand why?

My code works, but i dont know what about quality…

function palindrome(str) {
// Good luck!

str = str.toLowerCase().replace(/[]/g, ‘\’).replace(/[\s_.,-]/g, ‘’);
// return str;
var strReverse = str.split(’’).reverse().join(’’);

if (strReverse == str) {
return true;
} else {
return false;
}
}

palindrome(“eye”);

This is what I did. Works perfect, not sure about its efficiency though. Would love some feedback!

function palindrome(str) {
str = str.replace(/[`~!@#\$%^&*()_|+-=?;:’",.<>{}[]\/\s]/g,’’);
str = str.toLowerCase();
var straightArray = [];
var reverseArray = [];
straightArray = str.split("");
reverseArray = straightArray.slice(0);
reverseArray.reverse();
straightArray = straightArray.join("");
reverseArray = reverseArray.join("");
// Good luck!
if(reverseArray == straightArray){
return true;
} else {
return false;
}
}

## Single return statement solution:

```return str.match(/[a-zA-Z0-9]/g).join('').toLowerCase() == str.match(/[a-zA-Z0-9]/g).reverse().join('').toLowerCase();```
2 Likes

Because you have not filtered non-alphanumeric characters (punctuation, spaces and symbols) in the string.

“1 eye for of 1 eye” != “eye 1 fo rof eye 1”

What do you guys think of my solution?

``````function palindrome(str) {
``````

var scrubbed = str.replace(/[^a-zA-Z0-9]/g, “”).toLowerCase().split(’’);
var scrubbedReversed = str.replace(/[^a-zA-Z0-9]/g, “”).toLowerCase().split(’’).reverse();
if (scrubbedReversed.join(’’) === scrubbed.join(’’)) {
return true;
}
return false;
}

Hi there peeps, this is my first contribution, my solution to the palindrome problem. I think it falls into the Basic Solution category. Any feedback will be welcome

function palindrome(str) {
// Good luck!
str = str.replace(/[^0-9a-zA-Z]/gi, ‘’).toLowerCase();

var strlength = str.length;
var halfway;

if (strlength % 2 == 0) // even number of characters
{
halfway = strlength/2;
}
else
{
halfway = (strlength - 1)/2;
}
var match = 0; // counter for the number of matching pairs

``````for( var i = 0; i < halfway; i++)
{
if(str.charAt(i) == str.charAt(strlength - i-1))
match++; // keep matching characters at either end of string
// working towards centre.
}
if (match == halfway)
return true;
else
return false;
``````

}

palindrome(“eye”);