Palindrome test in jQuery
by Matthew Day
HTML
<input id="theInput" type="text" />
<button>Check for Palidrome</button>
<div id="output"></div>
CSS
/*
Write a function that given a string will test that string to see if it's a palindrome (i.e. the characters from the beginning are the same as the end).
An example of a palindrome would be "mom" or "dad" or a really big one would be "able was I ere I saw elba".
The function should just return a boolean indicating true for if it's a palindrome and false if it's not.
JavaScript
(function($) {
let app = {
init: function() {
app.paliTest();
},
paliTest: function() {
$(document).on('click', 'button', function() {
let input = $('#theInput').val().replace(/\s/g, '').toLowerCase();
let reverse = input.split("").reverse().join("").replace(/\s/g, '').toLowerCase();
let theLength = reverse.length - 1;
let isPali = false;
//console.log('A',input, reverse)
let theIndices = input.split("").map( (value, index) => {
//console.log(reverse.indexOf(value))
return reverse.indexOf(value);
});
for(let i = 0; i <= theLength; i ++) {
if(theIndices[i] != theIndices[theLength - i]) {
isPali = false;
//console.log('false', theIndices[i], theIndices[theLength - i]);
break;
} else {
isPali = true;
//console.log('true', theIndices[i], theIndices[theLength - i])
}
}
$('#output').empty().append(`<p>${isPali}</p>`);
});
}
}
$(document).ready(function() {
app.init();
})
})(window.jQuery);