5

The requirements for this task are that the code is returns a 'true' or 'false' for an input string. The string can be a simply word or a phrase. The other question does not address these needs. Please reopen and answer here. I am working on a function to check if a given string is a palindrome. My code seems to work for simple one-word palindromes but not for palindromes that feature capitalization or spaces.

function palindrome(str) 
{
    var palin = str.split("").reverse().join("");

    if (palin === str){
        return true;
    } else {
        return false;
    }
}   

palindrome("eye");//Succeeds
palindrome("Race car");//Fails
Austin Hansen
  • 364
  • 1
  • 6
  • 17
  • That question is asking how to generate palindromes, not check if two strings are palindromes given the criteria above. If we can get this reopened, I'll post this as an answer: `function isPalindrome(str) { str = str.replace(/\s/g, '').toLowerCase(); return str === str.split('').reverse().join(''); }` – Alexander O'Mara Jun 27 '15 at 16:56
  • @AlexanderO'Mara you are on the right track here. i need help understanding how to use regexpressions in javascript and use them here to remove white space and any punctuation as well as any uppercase letters. I wish they would reopen this question as the other question is definitely different. – Austin Hansen Jun 27 '15 at 17:05
  • @jfriend00 can you reopen this. not a duplicate – Austin Hansen Jun 27 '15 at 17:05
  • For handling punctuation, you could only keep work-like characters. `function isPalindrome(str) { str = str.replace(/\W/g, '').toLowerCase(); return str === str.split('').reverse().join(''); }` – Alexander O'Mara Jun 27 '15 at 17:08
  • ok perfect. thank you so much @AlexanderO'Mara! Two quick questions: 1) does '/' start and end a regex? 2) would '\W' handle whitespace and punctuation all in one shot since they are both non work-like characters? – Austin Hansen Jun 27 '15 at 17:09
  • The question this is marked a dup of contains lots of answers that show how to detect a palindrome true/false. It also contains code for generating a large palindrome for performance testing, but this question is answered there. If you search, here are at least 20 other dups too. This is a very popular question and easy to search for. – jfriend00 Jun 27 '15 at 17:10
  • I searched and reviewed the thread you indicated and i am not the only one who feels they are definitely different. it doesnt matter, i received the help needed and you maintain your stack overflow nazi oversight; good work! @jfriend00 – Austin Hansen Jun 27 '15 at 17:12
  • There are hundreds of other dups. Just trying to help keep the forum tidy per the rules. I will reopen and maybe someone else can mark a better dup as I'm now mobile and can't search at the moment. – jfriend00 Jun 27 '15 at 17:15
  • or you could have just let @AlexanderO'Mara give his solid explanation and answer, allowing me to learn and others as well. – Austin Hansen Jun 27 '15 at 17:16
  • In fairness, there is actually one answer in that other question that works for your needs: http://stackoverflow.com/a/22343082/3155639 The question description appears to include that use case as well, if not the title. – Alexander O'Mara Jun 27 '15 at 17:17
  • Lots of dups of an extremely popular question is not in the best interests of the forum. If u want to argue that you can take it up on Meta. That is not my policy. Also, if you think your question is unique, then you can edit it to make sure its unique requirements are very clearly specified and clearly point out why your question is unique. – jfriend00 Jun 27 '15 at 17:18

9 Answers9

9

First the string is converted to lowercase. Also, the characters that are not the alphabet are removed. So the string comparison becomes a array, then invert it, and convert it to string again.

Step 1: str1.toLowerCase().replace(...) => "Race car" => "race car" => "racecar"
Step 2: str2.split("") => ["r","a","c","e","c","a","r"] => .reverse().join() => "racecar"
Result: str1 === str2

function palindrome(str) {
   str = str.toLowerCase().replace(/[^a-z]+/g,"");
   return str === str.split("").reverse().join("")
}

alert(palindrome("eye")); //true
alert(palindrome("Race car")); //true
alert(palindrome("Madam, I'm Adam")); //true
4

Something like if (word === word.split('').reverse().join('')) {/*its a palindrome!*/} I'd say

An isPalindrome String extention:

String.prototype.isPalindrome = function () {
  var cleaned = this.toLowerCase().match(/[a-z]/gi).reverse();
  return cleaned.join('') === cleaned.reverse().join('');
}

var result = document.querySelector('#result');
result.textContent = "'eye'.isPalindrome() => " + 'eye'.isPalindrome() +
                     "\n'Something'.isPalindrome() => " + 'Something'.isPalindrome() +
                     "\n'Race Car'.isPalindrome() => " + 'Race Car'.isPalindrome() +
                     "\n'Are we not drawn onward, we few, drawn onward to new era?'.isPalindrome() => " + 
                        'Are we not drawn onward, we few, drawn onward to new era?'.isPalindrome() +
                     "\n'Never even or odd'.isPalindrome() => " + 'Never even or odd'.isPalindrome() +
                     "\n'Never odd or even'.isPalindrome() => " + 'Never odd or even'.isPalindrome();
;
<pre id="result"></pre>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
2
function palindrome(str) {
    let letters = str.split('').filter(function (str) {
        return /\S/.test(str);
    });
    let reversedLetters = str.split('').reverse().filter(function (str) {
        return /\S/.test(str);
    });

    for (let i = 0; i < letters.length; i++) {
        if (letters[i].toLowerCase() !== reversedLetters[i].toLowerCase()) {
            return false;
        }
    }
    return true;
}
console.log(palindrome("eye")); //true
console.log(palindrome('Race car')); //true
Adam Morsi
  • 351
  • 1
  • 7
1
const palindromes = arrayOfWords.filter((item) => {
    return item === item.split('').reverse().join('');
})

This is an example :-)

stefan
  • 35
  • 3
0
function palindrome(str) {

  var st='';    
  st=str.replace(/[^a-z0-9]/ig,"").toLowerCase();    
  var arr=[];    
  arr=st.split('');    
  arr=arr.reverse();    
  var strr='';    
  strr=arr.join('');
  if(strr==st) {
     return true;
 }
 return false;
}    
palindrome("A man, a plan, a canal. Panama");//calling the function
Gaurav Srivastava
  • 3,232
  • 3
  • 16
  • 36
0

//1. change the string to an array //2. use the reverse method //3. return the array as a string //4. return input= new reversed string

var lowerCasedString = inputString.toLowerCase(); var reversedString = lowerCasedString.split("").reverse().join(""); return reversedString === lowerCasedString;
}
hope this would be helpful:

Yakir Fitousi
  • 537
  • 3
  • 12
0

Palindrome using ES6

const checkPalindrome=(str)=> {
  return str.toLowerCase().trim() === str.toLowerCase().trim().split('').reverse().join('');
}
console.log(checkPalindrome("Level "))
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
0

As easy as possible!

function checkStrForPalindorme(string) {
  const str = string.toLowerCase().trim();
  const reversedStr = str.split("").reverse().join("");

  return str === reversedStr;
}

console.log(checkStrForPalindorme("aaffaa "))
console.log(checkStrForPalindorme("dummy"))
Sardorek Aminjonov
  • 724
  • 2
  • 7
  • 16
0

I have created a lookup object first and then analyze the frequency of each lookup item

if the str = "PEEPs", then lookUp = {p:2, e:2, s:1}

Please refer to the following function for more details

function checkPlaindrome(str) {
  const lookUp = {};
  // Create the lookUp object
  for (let char of str.toLowerCase().trim()) {
    if (char !== " ") lookUp[char] = ++lookUp[char] || 1;
  }
  // Analyse the lookup object
  const singleCharCheck = Object.values(lookUp).filter((val) => val === 1);
  const findalSingleCharCheck =
    singleCharCheck.length === 0 || singleCharCheck.length === 1;
  const noneSingleCharCheck =
    Object.values(lookUp)
      .filter((val) => val !== 1)
      .filter((val) => val % 2 !== 0).length === 0;

  return findalSingleCharCheck && noneSingleCharCheck;
}

const r = checkPlaindrome("w wPEEPs"); // true
const r1 = checkPlaindrome("w PEEPs"); // false
Nuwa
  • 461
  • 4
  • 10