Skip to content

Instantly share code, notes, and snippets.

@gidhon
Created December 3, 2021 02:29
Show Gist options
  • Save gidhon/6c957a9fedca8e54b80d63b956243836 to your computer and use it in GitHub Desktop.
Save gidhon/6c957a9fedca8e54b80d63b956243836 to your computer and use it in GitHub Desktop.
palindrome checker
/*
* @param String
* Using built-in methods, return true if a given string is a palindrome.
**/
function palindrome(str) {
const invalid = /[\W]/g;
const normalized = str.toLowerCase().replace(invalid, '');
const reversed = normalized.split('').reverse().join('');
return normalized === reversed;
}
/*
* @param String
* Using a for loop, return true if a given string is a palindrome.
**/
function palindromeForLoop(str) {
let reversed = [];
const invalid = /[\W]/g;
const normalized = str.toLowerCase().replace(invalid, '');
for (let i = 0, j = normalized.length; i < j; i++) {
reversed.push(normalized[j - i - 1])
}
reversed = reversed.join('');
return normalized === reversed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment