Let's clarify what this word means. A palindrome – literally "reversal" (from Greek παλινδρομέω – to return) – is a word or phrase that reads the same forward and backward, preserving its meaning.
Goal: create a function that checks whether a string is a palindrome. For example:
var str = 'abcdedcba',
str2 = 'abcded';
isPalindrome(str); // -> yes
isPalindrome(str2); // -> no
The function should return the string answer – 'yes' or 'no'.
function isPalindrome(str) {
var strLen = str.length,
strReverse = str.split('').reverse().join(''); // Split the string into characters, reverse the array, and join back into a string
if (strReverse == str) {
return 'yes';
} else {
return 'no';
}
}
test = isPalindrome('abcdedcba');
test2 = isPalindrome('abcded');
console.log(test);
console.log(test2);
document.write('isPalindrome result: ' + 'str - ' + test + ' str2 - ' + test2);
Alternative palindrome check – character‑by‑character comparison from start and end of the string:
function isPalindrome(str) {
var strLen = str.length;
var result = '';
for (var i = 0; i < strLen; i++) {
if (str[i] === str[strLen - 1 - i]) { // Compare characters from the start and end of the string
result = 'yes';
} else {
result = 'no';
return result;
}
}
return result;
}
test = isPalindrome('abcdedcba');
test2 = isPalindrome('abcded');
console.log(test);
console.log(test2);
document.write('isPalindrome result: ' + 'str - ' + test + ' str2 - ' + test2);