here's the problems with your code
function palindrome(str) {{
remove the second {
- you declare
regex
but never use it
/\W/g.remove;
... what does this do? a regex doesn't have a remove property
toLowerCase
is a function, that returns a new value - what you do doesn't call the function, nor does it store the result of calling the function
- remove this line
- OK
- don't make this a
const
because you can't change const's - also, naming a variable the same as the function it is in can cause confusion - as you'll see
- this will cause an infinite loop, you need
i--
to decrement i
on each loop
- OK
- OK
- OK
- OK
- You need to call the function - it's confusing because your variable name
- OK
- OK
- OK
- OK
- This calls the function, but does nothing with the result
So, the resulting fixed code is:
function palindrome(str) {
let regex = /\W/g;
str = str.toLowerCase().replace(regex, '');
function reverseString(str) {
let reverseString = "";
for (let i = str.length - 1; i >= 0; i--) {
reverseString += str[i];
}
return reverseString;
}
if (str === reverseString(str)) {
return true;
}
return false;
}
const result = palindrome("eye");
console.log(result)
But, no need for that inner function
function palindrome(str) {
const regex = /\W/g;
let reverseString = "";
str = str.toLowerCase().replace(regex, '');
for (let i = str.length - 1; i >= 0; i--) {
reverseString += str[i];
}
if (str === reverseString) {
return true;
}
return false;
}
const result = palindrome("eye");
console.log(result)
Though I'd probably write it like
function palindrome(str) {
str = str.toLowerCase().replace(/\W/g, '');
return str === str.split('').reverse().join('');
}
const result = palindrome("eye");
console.log(result);