Your regex is correct. Your code/fiddle does not work because the strings have different casing (Racecar vs racecar).
If you also convert the nospace variable to lowercase, it works:
function palindrome(str) {
// Good luck!
var nospace = str.replace(" ", "").toLowerCase();
// ^^^^^^^^^^^^^^--- added this
var reverse = str.split('').reverse().join('');
var change = reverse.toLowerCase();
console.log(change);
var regexp = /[^A-Za-z]|\s+/g;
var x = change.replace(regexp, "");
if (nospace == x) {
return true;
} else {
return false;
}
}
console.log(palindrome("Race car"));
See updated fiddle here.
Now, your code could use some other improvements.
The regex "strip everything that is not a letter" regex (/[^A-Za-z]|\s+/g) could be simplified to /[^A-Za-z]/g. But you may really not need it at all (I don't know your requirements, you may still need it if your requirements really want you to remove non-letters, not just spaces).
Your first nospace var only replaces the first white space from the input. Using a regex there would make it replace all of them (only do this if this is really what you wanted): str.replace(" ", "") becomes str.replace(/\s+/g, "").
Also, since you already removed the spaces in nospace, you could just reverse it (instead of reversing the input and later removing its spaces). And then compare it.
Also the last if/else could be simplified to just a return statement. The final code would look something like this:
function palindrome(str) {
var nospace = str.replace(/\s+/g, "").toLowerCase();
var reverse = nospace.split('').reverse().join('').toLowerCase().replace(/[^a-z]/g, "");
// optional, depends on your requirements -------------^^^^^^^^^^^^^^^^^^^^^^^^
return nospace === reverse;
}
console.log(palindrome("R a c e c a r")); // output: true
JSFiddle here.