Learn how to check for Palindromes in strings with JavaScript.
A common interview question for Junior Developers is to create a JavaScript Palindrome Checker program.
(A palindrome is a word or series of characters that can be reversed and it reads exactly the same e.g. racecar, redder, madam, and refer)
This should be a really easy challenge as if you receive the given string, if it is exactly equal (character by character) to the original then it is a palindrome.
However, JavaScript, whilst it does provide you with many functions doesn’t provide you with one to reverse a string (although you can test strings directly for equality).
So we need a way to get a reverse copy of our input string.
Method 1 - Using a loop
const inputStr = 'Madam';
const isPalindrome = (inStr) =>
for (let i=0; i
In the above, we are looping through a string, analysing each character at the start of the string with the corresponding character at the end of the string.
If we get a mismatch, the function returns false otherwise we keep going until a true value is returned.
Method 2 - Converting to an array
const inputString = 'I did, did I?';
const isPalindrome = (inStr) => {
inStr = inStr.replace(/\W/g, '');
inStr = inStr.toLowerCase();
return inStr === inStr.split('').reverse().join('');
}
The other way is to convert the original string in to an array and then use the array reverse function to get an exact backwards copy of the string (once it’s been joined back together again).
This way we’re kind of faking our own String.reverse function.
In the above code it’s also worth removing anything that’s not an alphanumeric character (like the whitespace and the special characters) with a RegEx and converting the whole string to lower case.