Reputation:
I want to find if the user entered string is a Palindrome or not using arrow functions. But the code I have written is not showing an output....I dont understand whats wrong pls help....
var name = prompt("Enter Name: ");
const isPalindrome = name => {
const midPoint = name.length / 2;
for (let i = 0; i < midPoint && i < name.length; i++) {
if (name[i] != name[name.length - 1 - i]) {
console.log(" Not Palindrome");
}
}
console.log("Palindrome");
}
Upvotes: 0
Views: 1018
Reputation: 1926
You can check for palindrome without a for loop.
function isPalindrome(string) {
const toArray = string.replace(/ /g, '').toLowerCase().split('');
const reverseArray = toArray.slice().reverse();
const original = toArray.join('');
const reversed = reverseArray.join('');
if (original === reversed) {
return true;
} else {
return false;
};
}
isPalindrome('WORD HERE');
Upvotes: 2
Reputation: 20006
All you have to do is just to call the function with the user input.
Also remember to return
from the function once the input is not found as a palindrome. Else function will log both Not Palindrome
and Palindrome
when the input is not palindrome
var name = prompt("Enter Name: ");
const isPalindrome = name => {
const midPoint = name.length / 2;
for (let i = 0; i < midPoint && i < name.length; i++) {
if (name[i] != name[name.length - 1 - i]) {
console.log(" Not Palindrome");
return;
}
}
console.log("Palindrome");
}
isPalindrome(name);
Upvotes: 0