1function palindrome(str) {
2
3 var len = str.length;
4 var mid = Math.floor(len/2);
5
6 for ( var i = 0; i < mid; i++ ) {
7 if (str[i] !== str[len - 1 - i]) {
8 return false;
9 }
10 }
11
12 return true;
13}
14
1function isPalindrome(str, ignoreSpecialChars=true) {
2 if (typeof str !== 'string' || str.length === 0)
3 throw new Error("Invalid input");
4
5 //Here, let's first clean the string of all punctuation and weird characters
6 function cleanString(string) {
7 string = string.toLowerCase();
8 const validChars = '1234567890qwertyuiopasdfghjklzxcvbnm';
9 let newStr = '';
10 for (let char of string) {
11 if (validChars.indexOf(char) > -1) {
12 newStr += char;
13 }
14 }
15 //return a strictly alphanumeric version of the string. No spaces or other special characters.
16 return newStr;
17 }
18
19 //Take note that after line 18, str will be lowercase. That's important.
20 str = ignoreSpecialChars ? cleanString(str) : str.toLowerCase();
21
22 //loop only halfway through the string as we are only comparing 1st half to 2nd half
23 for (let i = 0; i < (str.length /2); i++) {
24 //return false if any non-match chars are found. (we're comparing lowercase to lowercase here)
25 if (str[i] !== str[str.length - 1 - i])
26 return false;
27 }
28
29 //if loop finishes, that means it is a palindrome. So we return true
30 return true;
31}
32
33isPalindrome("Madam, I'm Adam!!") // will return true
34isPalindrome("Madam, I'm TBG, not Adam!!") // will return false
35
36isPalindrome("Madam, I'm Adam!!", false) // will return false
37isPalindrome("Racecar", false) // will return true
38
1function palindrome(str) {
2 var re = /[\W_]/g;
3 var lowRegStr = str.toLowerCase().replace(re, '');
4 var reverseStr = lowRegStr.split('').reverse().join('');
5 return reverseStr === lowRegStr;
6}
7palindrome("A man, a plan, a canal. Panama");
1function palindrome(str) {
2 var re = /[^A-Za-z0-9]/g;
3 str = str.toLowerCase().replace(re, '');
4 var len = str.length;
5 for (var i = 0; i < len/2; i++) {
6 if (str[i] !== str[len - 1 - i]) {
7 return false;
8 }
9 }
10 return true;
11}
12palindrome("A man, a plan, a canal. Panama");
1function palindrome(str) {
2 var splitted = str.split("");
3 var reversed = splitted.reverse("");
4 var joined = reversed.join("");
5 return joined.toLowerCase().replace(/[^0-9a-z]/gi, '') == str.toLowerCase().replace(/[^0-9a-z]/gi, '')
6}
7