The best way to solve “Palindrome” challenge.
Target
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
function isPalindrome(string) {
}isPalindrome("eye"); // return true
Example 1:
Input: "Madam, I'm Adam."
Output: true
Example 2:
Input: "race a car"
Output: false
Solution
Step 1
Convert all characters to lower case — ignoring cases
string.toLowerCase()
Step 2
Remove all non-alphanumeric characters — only alphanumeric characters
string.replace(/[^A-Za-z0-9]/g, '')orstring.replace(/[\W_]/g, '')
\W is equivalent to [^A-Za-z0–9_]
Step 3
Reverse the string — it will match the original one if it is a palindrome
string.split('').reverse().join('')
Code
function isPalindrome(string) { const lowerString = string.toLowerCase(); const characters = lowerString.replace(/[\W_]/g, ''); const reverseCharacters = characters.split('').reverse().join(''); return characters === reverseCharacters;}console.log(isPalindrome("Madam I'm Adam.")); // trueconsole.log(isPalindrome("race car")); // trueconsole.log(isPalindrome("Coding JavaScript")); // false
Using For … Loop
function isPalindrome(string) { const lowerString = string.toLowerCase(); const characters = lowerString.replace(/[\W_]/g, ''); const len = characters.length; for (var i = 0; i < len / 2; i++) { if (characters[i] !== characters[len - 1 - i]) return false; } return true;}