58

I have the following:

function checkPalindrom(palindrom)
{

    for( var i = palindrom.length; i > 0; i-- )
    {
        if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
        {
            document.write('the word is palindrome.');
        }else{
            document.write('the word is not palindrome!');
        }
    }
}
checkPalindrom('wordthatwillbechecked');

What is wrong with my code? I want to check if the word is a palindrome.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
emcee22
  • 1,851
  • 6
  • 23
  • 32
  • 8
    Why do you think there is something wrong with your code? What happens and what do you expect to happen? – Felix Kling Feb 11 '13 at 13:58
  • 2
    From wikipedia: "Allowances may be made for adjustments to capital letters, punctuation, and word dividers". – Mojtaba Jan 21 '16 at 18:01

45 Answers45

176

Maybe I will suggest alternative solution:

function checkPalindrom (str) {
  return str == str.split('').reverse().join('');
}

UPD. Keep in mind however that this is pretty much "cheating" approach, a demonstration of smart usage of language features, but not the most practical algorithm (time O(n), space O(n)). For real life application or coding interview you should definitely use loop solution. The one posted by Jason Sebring in this thread is both simple and efficient (time O(n), space O(1)).

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 4
    This is clearly the simplest code, although maybe not the most [efficient solution](http://jsperf.com/is-palindrome/3). But for someone writing code like the original, perhaps simpler steps toward a good solution are of better help than a leap toward a great solution? – Scott Sauyet Feb 11 '13 at 19:02
  • 3
    You are right. My variant is not teaching OP how to program (there are 5 other great answers more relevant to this original problem), i'm just showing different approach to the problem. And the ability to invent non-obvious ways is also very important. – dfsq Feb 11 '13 at 21:01
  • True, and no offense meant. That is clearly the cleanest solution available. – Scott Sauyet Feb 11 '13 at 22:05
  • 5
    you need some extra code in there if the string has spaces or punctuation, fyi – Jason Aug 13 '14 at 19:00
  • +1 @dfsq A job interview question I passed but in a more conventional way made me obsess on this and iterate on it till I came up with my answer on here. JavaScript is so cool what you can do. If you have tips to make it even shorter because of your high rep, please do, such as bit shifting or whatever trick I didn't think of. – King Friday Aug 14 '14 at 15:52
  • 1
    revString("eye") => true while revString("race car") => false while a palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing. How we could improve this? – Hamza Bahlaouane Sep 01 '15 at 23:54
  • 1
    @HamzaBahlaouane The easiest way is to use .toLowerCase (or .toUpperCase) along with a regex that removes the problematic characters, before running the comparision. So, before line 2, add something like ``str = str.toLowerCase().replace( /[\s~`!@#$%^&*()-_+=[\]{}\\|:;"',<>.?\/\u2000-\u206F\u2E00-\u2E7F\u3000-\u303F]/g, '');`` or, if you don't care about Unicode support, ``str = str.toLowerCase().replace(/\W/g, '')`` – trlkly May 05 '16 at 12:06
  • Also, this won't work on numbers. We could add a snippet that converts any number argument given to string before applying: `function checkPalindrom(str) { var num = str; if (typeof num !== 'string'){ num = num.toString(); } return num === num.split('').reverse().join(''); }` – jswebb Jun 01 '17 at 17:07
  • Uniparental disomy? – Phu Ngo May 22 '20 at 03:34
  • clean,,, genius – thedanotto Jul 27 '21 at 14:58
53

25x faster than the standard answer

function isPalindrome(s,i) {
 return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}

use like:

isPalindrome('racecar');

as it defines "i" itself

Fiddle: http://jsfiddle.net/namcx0yf/9/

This is ~25 times faster than the standard answer below.

function checkPalindrome(str) {
  return str == str.split('').reverse().join('');
}

Fiddle: http://jsfiddle.net/t0zfjfab/2/

View console for performance results.

Although the solution is difficult to read and maintain, I would recommend understanding it to demonstrate non-branching with recursion and bit shifting to impress your next interviewer.

explained

The || and && are used for control flow like "if" "else". If something left of || is true, it just exits with true. If something is false left of || it must continue. If something left of && is false, it exits as false, if something left of a && is true, it must continue. This is considered "non-branching" as it does not need if-else interupts, rather its just evaluated.

1. Used an initializer not requiring "i" to be defined as an argument. Assigns "i" to itself if defined, otherwise initialize to 0. Always is false so next OR condition is always evaluated.

(i = i || 0) < 0

2. Checks if "i" went half way but skips checking middle odd char. Bit shifted here is like division by 2 but to lowest even neighbor division by 2 result. If true then assumes palindrome since its already done. If false evaluates next OR condition.

i >= s.length >> 1

3. Compares from beginning char and end char according to "i" eventually to meet as neighbors or neighbor to middle char. If false exits and assumes NOT palindrome. If true continues on to next AND condition.

s[i] == s[s.length-1-i]

4. Calls itself again for recursion passing the original string as "s". Since "i" is defined for sure at this point, it is pre-incremented to continue checking the string's position. Returns boolean value indicating if palindrome.

isPalindrome(s,++i)

BUT...

A simple for loop is still about twice as fast as my fancy answer (aka KISS principle)

function fastestIsPalindrome(str) {
  var len = Math.floor(str.length / 2);
  for (var i = 0; i < len; i++)
    if (str[i] !== str[str.length - i - 1])
      return false;
  return true;
}

http://jsfiddle.net/6L953awz/1/

King Friday
  • 25,132
  • 12
  • 90
  • 84
  • 1
    This returns false: `console.log(isPalindrome('Avid diva'));` – ErickBest Sep 01 '14 at 11:59
  • 8
    `isPalindrome('Avid diva'.toLowerCase())` returns `true`. – Wildhoney May 12 '15 at 10:58
  • 64
    25 times uglier – Chris Hawkes Aug 19 '16 at 20:48
  • 13
    @ChrisHawkes I agree 100%. The main point was to educate on language features and also provide the point at the bottom showing that plain programming is both faster and easier to look at. – King Friday Aug 19 '16 at 20:57
  • 4
    Yeah I should clarify it was extremely crafty and way over my head :) – Chris Hawkes Aug 19 '16 at 20:58
  • 1
    Though one might pedantically point out that it still doesn't solve for the spacing, punctuation and letter capitalization allowances of a true palindrome. – Paul Nov 21 '16 at 18:05
  • @Paul true. This was one of those odd times where I had a job interview where they asked this, then I went nuts and over impressed them, then I decided not to take the job, then got a better one based on this post. – King Friday Nov 21 '16 at 18:07
  • For giggles I went ahead and updated your most efficient function and added some tests here: https://github.com/pvencill/palindrome. I didn't test for performance to see how much my additional regex slowed it down. – Paul Nov 21 '16 at 18:49
  • if you use recursion for something that might need to recurse 4000 or 10000 level deep, then it may stack overflow... you generally can do recursion if the size is smaller by `n / 2` every time, meaning that for even big number of n, the level will be a small number (due to log 100000000000000 base 2 merely just 46) – nonopolarity Apr 14 '17 at 00:17
  • Agreed. This is really just a walkthrough of features. If anyone does that long of a string to check a palindrome, wow, that's nuts right? – King Friday Apr 14 '17 at 00:19
  • 1
    The KISS code at the bottom of your post is A+. So few others recognize that you only need to check (at most) half of the string. – Mulan May 31 '17 at 01:01
12

The logic here is not quite correct, you need to check every letter to determine if the word is a palindrome. Currently, you print multiple times. What about doing something like:

function checkPalindrome(word) {    
    var l = word.length;
    for (var i = 0; i < l / 2; i++) {
        if (word.charAt(i) !== word.charAt(l - 1 - i)) {
            return false;
        }
    }
    return true;
}

if (checkPalindrome("1122332211")) {
    document.write("The word is a palindrome");
} else {
    document.write("The word is NOT a palindrome");
}

Which should print that it IS indeed a palindrome.

BeRecursive
  • 6,286
  • 1
  • 24
  • 41
  • @MG_Bautista both do different things, just like `==` and `===`. – KBN Feb 11 '13 at 14:18
  • !== does a type check on the inequality and in Javascript it is generally good practise to always use type checking operators. – BeRecursive Feb 11 '13 at 14:21
  • As an aside, you'd probably want `i < word.length / 2`, since any iterations after halfway through the word are redundant. – Andy E Feb 11 '13 at 14:40
  • @AndyE agreed, a poor oversight on my part in an attempt at speed – BeRecursive Feb 11 '13 at 14:43
  • The way it is, `if (checkPalindrome("Avid diva")) {` will print:`The word is NOT a palindrome` You need to force `lowercase` to cover words that have capitals... `word = word.toLowerCase()` .. Hope it helps. – ErickBest Sep 01 '14 at 12:07
11

First problem

= is assign == is compare

Second problem, Your logic here is wrong

palindrom.charAt(palindrom.length)-1

You are subtracting one from the charAt and not the length.

Third problem, it still will be wrong since you are not reducing the length by i.

epascarello
  • 204,599
  • 20
  • 195
  • 236
10

It works to me

function palindrome(str) {
  /* remove special characters, spaces and make lowercase*/
  var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();

  /* reverse removeChar for comparison*/
  var checkPalindrome = removeChar.split('').reverse().join('');

  /* Check to see if str is a Palindrome*/
   return (removeChar === checkPalindrome);
}
9

As a much clearer recursive function: http://jsfiddle.net/dmz2x117/

function isPalindrome(letters) {

    var characters  = letters.split(''),
        firstLetter = characters.shift(),
        lastLetter  = characters.pop();

    if (firstLetter !== lastLetter) {
        return false;
    }

    if (characters.length < 2) {
        return true;
    }

    return isPalindrome(characters.join(''));

}
Wildhoney
  • 4,969
  • 33
  • 38
9

SHORTEST CODE (31 chars)(ES6):

p=s=>s==[...s].reverse().join``
p('racecar'); //true

Keep in mind short code isn't necessarily the best. Readability and efficiency can matter more.

Max
  • 2,710
  • 1
  • 23
  • 34
  • 3
    Why does the empty template string `` work at the end? I have never seen this syntax before and do not understand why it is working here. – bubblez Apr 02 '17 at 17:18
  • 2
    because dumb – its's shorter than writing `.join('')` but dramatically hurts readability for the sake of making code shorter – Mulan May 30 '17 at 23:15
  • 2
    It's a template literal, (ab)used here to save two chars for parenthesis -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals] – John Hascall May 30 '17 at 23:23
  • It's a tagged template. Read this : http://www.ecma-international.org/ecma-262/6.0/#sec-tagged-templates – Max Jun 03 '19 at 04:37
  • This is also Unicode-aware because it splits characters, not UTF-16 code units. – Sebastian Simon May 14 '20 at 17:23
6

At least three things:

  • You are trying to test for equality with =, which is used for setting. You need to test with == or ===. (Probably the latter, if you don't have a reason for the former.)

  • You are reporting results after checking each character. But you don't know the results until you've checked enough characters.

  • You double-check each character-pair, as you really only need to check if, say first === last and not also if last === first.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
4
function checkPalindrom(palindrom)
{
   var flag = true;
   var j = 0;
    for( var i = palindrom.length-1; i > palindrom.length / 2; i-- )
    {
        if( palindrom[i] != palindrom[j] )
        {
           flag = false;
           break; // why this? It'll exit the loop at once when there is a mismatch.
        }
        j++;
    }
  if( flag ) {
  document.write('the word is palindrome.');
  }
  else {
document.write('the word is not palindrome.');
  }
}
checkPalindrom('wordthatwillbechecked');

Why am I printing the result outside the loop? Otherwise, for each match in the word, it'll print "is or is not pallindrome" rather than checking the whole word.

EDIT: Updated with changes and a fix suggested by Basemm.

KBN
  • 2,915
  • 16
  • 27
  • That won't work as you need to start from "length-1". also for efficiency u should stop at middle of string and not checking the whole string – Basemm Dec 27 '13 at 01:46
4

I've added some more to the above functions, to check strings like, "Go hang a salami, I'm a lasagna hog".

function checkPalindrom(str) {
    var str = str.replace(/[^a-zA-Z0-9]+/gi, '').toLowerCase();
    return str == str.split('').reverse().join('');
}

Thanks

Robin C Samuel
  • 1,215
  • 15
  • 33
4

The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.

Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.

isPalindrome():

Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.

for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.

Here's the code:

/**
 * TODO: If func counts out, let it return 0
 *  * Assume !isPalindrome (invert logic)
 */
function isPalindrome(S){
    var s = S
      , len = s.length
      , mid = len/2;
      , i = 0, j = len-1;

    while(i<mid){
        var l = s.charAt(i);
        while(j>=mid){
            var r = s.charAt(j);
            if(l === r){
                console.log('@while *', i, l, '...', j, r);
                --j;
                break;
            }
            console.log('@while !', i, l, '...', j, r);
            return 0;
        }
        ++i;
    }
    return 1;
}

var nooe = solution('neveroddoreven');  // even char length
var kayak = solution('kayak');  // odd char length
var kayaks = solution('kayaks');

console.log('@isPalindrome', nooe, kayak, kayaks);

Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.

Cody
  • 9,785
  • 4
  • 61
  • 46
4
function palindromCheck(str) {
    var palinArr, i,
        palindrom = [],

    palinArr = str.split(/[\s!.?,;:'"-()]/ig);

    for (i = 0; i < palinArr.length; i++) {
        if (palinArr[i].toLowerCase() === palinArr[i].split('').reverse().join('').toLowerCase() &&
            palinArr[i] !== '') {
            palindrom.push(palinArr[i]);
        }
    }
        return palindrom.join(', ');
}
console.log(palindromCheck('There is a man, his name! was Bob.')); //a, Bob

Finds and upper to lower case. Split string into array, I don't know why a few white spaces remain, but I wanted to catch and single letters.

brandonscript
  • 68,675
  • 32
  • 163
  • 220
Ilian Grekov
  • 51
  • 1
  • 4
3
  • = in palindrom[i] = palindrom.charAt(palindrom.length)-1 should be == or ===
  • palindrom.charAt(palindrom.length)-1 should be palindrom.charAt(palindrom.length - i)
fardjad
  • 20,031
  • 6
  • 53
  • 68
3

Sharing my fast variant which also support spaces

function isPalindrom(str) {
  var ia = 0;
  var ib = str.length - 1;
  do {
    if (str[ia] === str[ib]) continue;

    // if spaces skip & retry
    if (str[ia] === ' ' && ib++) continue;
    if (str[ib] === ' ' && ia--) continue;

    return false;
  } while (++ia < --ib);
  return true;
}
var palindrom="never odd or even";
var res = isPalindrom(palindrom);
document.getElementById('check').innerHTML ='"'+ palindrom + '"'+" checked to be :" +res;
<span id="check" />
Saffi Hartal
  • 49
  • 1
  • 4
3

Some above short anwsers is good, but it's not easy for understand, I suggest one more way:

function checkPalindrome(inputString) {

    if(inputString.length == 1){
        return true;
    }else{
        var i = 0;
        var j = inputString.length -1;
        while(i < j){
            if(inputString[i] != inputString[j]){
                return false;
            }
            i++;
            j--;
        }
    }
    return true;
}

I compare each character, i start form left, j start from right, until their index is not valid (i<j). It's also working in any languages

hien
  • 1,988
  • 2
  • 17
  • 13
3

One more solution with ES6

isPalin = str => [...str].every((c, i) => c === str[str.length-1-i]);
Sumer
  • 2,687
  • 24
  • 24
3

You can try the following

function checkPalindrom (str) {
      str = str.toLowerCase();
      return str == str.split('').reverse().join('');
    }

    if(checkPalindrom('Racecar')) {
        console.log('Palindrome');
    } else {
        console.log('Not Palindrome');
    }
w3outlook
  • 823
  • 6
  • 16
2
function checkPalindrom(palindrom)
{
  palindrom= palindrom.toLowerCase();
   var flag = true;
   var j;
   j = (palindrom.length) -1 ;
   //console.log(j);
   var cnt = j / 2;
   //console.log(cnt);
    for( i = 0; i < cnt+1 ; i++,j-- )
    {
        console.log("J is => "+j);
        console.log(palindrom[i] + "<==>" + palindrom[j]);
        if( palindrom[i] != palindrom[j] )
        {
           flag = false;
           break; 
        }


    }
  if( flag ) {
  console.log('the word is palindrome.');
  }
  else {
console.log('the word is not palindrome.');
  }
}
checkPalindrom('Avid diva');
weborion
  • 29
  • 3
  • Hi @weborion, could you *explain* your answer? You'll notice that petty much all the other answers have done accompanying text describing how they did what they did, any drawbacks, etc. Code-only answers are usually best avoided because they only serve to *give* a solution, and not help somebody *learn* from it as readily. – Wai Ha Lee Apr 26 '15 at 23:43
  • Hi Lee , Sorry new to StackOverFlow commenting , The Logic is it uses two pointers one run from Front (i.e. i=0 )and Another run from end (j= (palindrom.length) -1) , Front will go in upward direction and End in reverse, We do not need to check for whole array .So cnt= j/2 which is middle of array. Then check array[front-ponter] is equals array[end-ponter] if not end the loop if at the middle all the characters match string is Palindrome. Sorry With Code I was not able to put the comments earlier. – weborion Apr 28 '15 at 01:34
2

I'm wondering why nobody suggested this:

ES6:

// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
isPalindrom = (str = "") => {
  if (str[0] === str[str.length - 1]) {
    return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
  }

  return false;
}

alert(["aba", "acb", "aa", "abba", "s"].map((e, i) => isPalindrom(e)).join())

ES5:

// "aba" -> true
// "acb" -> false
// "aa" -> true
// "abba" -> true
// "s" -> true
function isPalindrom(str) => {
  var str = typeof str !== "string" ? "" : str;

  if (str[0] === str[str.length - 1]) {
    return str.length <= 1 ? true : isPalindrom(str.slice(1, -1))
  }

  return false;
}

alert(["aba", "acb", "aa", "abba", "s"].map(function (e, i) {
    return isPalindrom(e);
}).join());
elad.chen
  • 2,375
  • 5
  • 25
  • 37
2

Recursive Method:

var low;
var high;
var A = "abcdcba";  

function palindrome(A , low, high){
  A = A.split('');

 if((low > high) || (low == high)){
   return true;
 }

 if(A[low] === A[high]){
   A = A.join('');
   low = low + 1; 
   high = high - 1; 
   return palindrome(A , low, high);
 }
 else{
   return "not a palindrome";
 }
}

palindrome(A, 0, A.length-1);
Rohit
  • 41
  • 1
  • 5
2

I thought I'd share my own solution:

function palindrome(string){
    var reverseString = '';
    for(var k in string){
       reverseString += string[(string.length - k) - 1];
    }
  if(string === reverseString){
    console.log('Hey there palindrome');
  }else{
    console.log('You are not a palindrome');
  }
}
palindrome('ana');

Hope will help someone.

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
1

I found this on an interview site:

Write an efficient function that checks whether any permutation of an input string is a palindrome. You can ignore punctuation, we only care about the characters.

Playing around with it I came up with this ugly piece of code :)

function checkIfPalindrome(text) {
    var found = {};
    var foundOne = 0;
    text = text.replace(/[^a-z0-9]/gi, '').toLowerCase();
    for (var i = 0; i < text.length; i++) {
        if (found[text[i]]) {
            found[text[i]]++;
        } else {
            found[text[i]] = 1;
        }
    }
    for (var x in found) {
        if (found[x] === 1) {
            foundOne++;
            if (foundOne > 1) {
                return false;
            }
        }
    }
    for (var x in found) {
        if (found[x] > 2 && found[x] % 2 && foundOne) {
            return false;
        }
    }
    return true;
}

Just leaving it here for posterity.

Rudy
  • 2,323
  • 1
  • 21
  • 23
1

How about this, using a simple flag

function checkPalindrom(str){
   var flag = true;
   for( var i = 0; i <= str.length-1; i++){
    if( str[i] !== str[str.length - i-1]){
      flag = false;  
     }
    }
    if(flag == false){
      console.log('the word is not a palindrome!');   
    }
    else{
    console.log('the word is a palindrome!');
    }
}

checkPalindrom('abcdcba');
Rohit
  • 41
  • 1
  • 5
  • 2
    There's no point to continue iterating if `flag` is ever set to `false` – ie, just return `false` immediately whenever the characters don't match – Mulan May 31 '17 at 00:12
1

(JavaScript) Using regexp, this checks for alphanumeric palindrome and disregards space and punctuation.

function palindrome(str) {
  str = str.match(/[A-Za-z0-9]/gi).join("").toLowerCase();
  //  (/[A-Za-z0-9]/gi) above makes str alphanumeric

  for(var i = 0; i < Math.floor(str.length/2); i++) { //only need to run for half the string length 
    if(str.charAt(i) !== str.charAt(str.length-i-1)) { // uses !== to compare characters one-by-one from the beginning and end
      return "Try again.";
    }
  }
  return "Palindrome!";
}
palindrome("A man, a plan, a canal. Panama.");
//palindrome("4_2 (: /-\ :) 2-4"); // This solution would also work on something like this.
N Schnupp
  • 11
  • 2
1

Loop through the string characters both forwards (i) and backwards (j) using a for loop. If at any point the character at str[i] does not equal str[j] - then it is not a palindrome. If we successfully loop through the string then it is a palindrome.

function isPalindrome(str) {
  for(var i = 0, j = str.length - 1; i < str.length; i++, j--) {
    if (str[i] !== str[j]) return false
  }

  return true
}
1
`
function checkPalindrome (str) {
    var str = str.toLowerCase();
    var original = str.split(' ').join('');
    var reversed = original.split(' ').reverse().join('');

  return (original === reversed);
}
`
charlchad
  • 3,381
  • 1
  • 16
  • 9
1

This avoids regex while also dealing with strings that have spaces and uppercase...

function isPalindrome(str) {
    str = str.split("");

    var str2 = str.filter(function(x){ 
        if(x !== ' ' && x !== ',') {
            return x;
        }
    });

    return console.log(str2.join('').toLowerCase()) == console.log(str2.reverse().join('').toLowerCase());
};

isPalindrome("A car, a man, a maraca"); //true
alexoviedo999
  • 6,761
  • 1
  • 26
  • 17
1

Using recursion:

function isPalindromeRecursive(str) {
  const isLessThan2 = str.length < 2;
  const firstAndLastEqual = str.slice(0, 1) === str.slice(-1);
  return !isLessThan2 && firstAndLastEqual 
    ? isPalindromeRecursive(str.slice(1, -1)) 
    : isLessThan2;
}
aashah7
  • 2,075
  • 1
  • 17
  • 24
1
function myPolidrome(polidrome){
 var string=polidrome.split('').join(',');
 for(var i=0;i<string.length;i++){
    if(string.length==1){
     console.log("is polidrome");
   }else if(string[i]!=string.charAt(string.length-1)){
     console.log("is not polidrome");
     break;
  }else{
     return  myPolidrome(polidrome.substring(1,polidrome.length-1));
  }
  }
  }
myPolidrome("asasdsdsa");
1

Thought I will share my solution using Array.prototype.filter(). filter() filters the array based on boolean values the function returns.

var inputArray=["","a","ab","aba","abab","ababa"]
var outputArray=inputArray.filter(function isPalindrome(x){
  if (x.length<2) return true;
  var y=x.split("").reverse().join("");
  return x==y;
})
console.log(outputArray);
kirancodify
  • 695
  • 8
  • 14
1

This worked for me.

var number = 8008
number = number + "";
numberreverse = number.split("").reverse().join('');
console.log ("The number if reversed is: " +numberreverse);
if (number == numberreverse)
    console.log("Yes, this is a palindrome");
else
    console.log("Nope! It isnt a palindrome");
Thomas Rollet
  • 1,573
  • 4
  • 19
  • 33
Emjey
  • 2,038
  • 3
  • 18
  • 33
1

Here is a solution that works even if the string contains non-alphanumeric characters.

function isPalindrome(str) {
    str = str.toLowerCase().replace(/\W+|_/g, '');
    return str == str.split('').reverse().join('');
}
Valery Melou
  • 60
  • 2
  • 12
1

Writing the code for checking palindromes following the best practices of JavaScript:

(function(){
 'use strict';
 
 var testStringOne = "Madam";
 var testStringTwo = "testing";
 var testNull = null;
 var testUndefined;
 
 console.log(checkIfPalindrome(testStringOne));
 console.log(checkIfPalindrome(testStringTwo));
 console.log(checkIfPalindrome(testNull));
 console.log(checkIfPalindrome(testUndefined));
 
 function checkIfPalindrome(testStringOne){
  
  if(!testStringOne){
   return false;
  }
  
  var testArrayOne = testStringOne.toLowerCase().split("");
  testArrayOne.reverse();
  
  if(testArrayOne.toString() == testStringOne.toLowerCase().split("").toString()){
   return true;
  }else{
   return false;
  }
 }
 
})();
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
1

If you want efficiency and simplicity, I recommend this approach:

function Palindrome(str = '') {
    let len = str.length;
    let i = -1;

    if (len < 3) { 
        return false;
    }
  
    while (len-- > i++) {
        if (str[i] !== str[len]) {
            return false;
        }
    }

    return true;
}

console.log(Palindrome('aba'))//true
console.log(Palindrome('abc'))//false
WesleyAC
  • 523
  • 6
  • 11
1

Some notable logics for Palindrome check

Filter alphaNumeric and make case insensitive

alnum filteration

str = text.toLowerCase().replace(/[^A-Za-z0-9]/g,''); 

non-word chars filteration

str = text.toLowerCase().replace(/[\W_]/g,'');

Palindrome logics

inbuilt methods [shorter]

const isPalindrome = (str) => str === [...str].reverse().join('');

all chars iteration [ simpler ]

const isPalindrome = (str) => {
    let rev = "";
    length = str.length;
    while(length--){
        rev += str[length];
    }
    return str === rev;
}

2 pointer approach [ performance ]

const isPalindrome = (str) => {
    const length = str.length;
    const halfLength = Math.floor(length /2);
    for(let i=0;i<halfLength; i++){
        if(str[i] !== str[length-1-i]){
            return false;
        }
    }
    return true;
}

recursive [eloquent]

const isPalindrome = (str) => {
const length = str.length;
    if (length <= 1){
        return true;
    } else if (str.charAt(0) !== str.slice(-1)){
        return false;
    } else{
        return isPalindrome(str.substring(1,length-1));
    } 
}

// inbuilt methods [shorter]
const isPalindrome1 = (text) => {
  let str = text.toLowerCase().replace(/[^A-Za-z0-9]/g, '')
  return str === [...str].reverse().join('');
}

// native logic [easier]
const isPalindrome2 = (text) => {
  let str = text.toLowerCase().replace(/[^A-Za-z0-9]/g, '')
  let rev = "";
  length = str.length;
  while(length--){
    rev += str[length];
  }
  return str === rev;
}

// 2 pointer approach [performance]
const isPalindrome3 = (text) => {
  let str = text.toLowerCase().replace(/[\W_]/g,'');
  const length = str.length;
  const halfLength = Math.floor(length /2);
  for(let i=0;i<halfLength; i++){
    if(str[i] !== str[length-1-i]){
      return false;
    }
  }
  return  true;
}

// recursive [ eloquent ]
const isPalindrome4 = (text) => {
  let str = text.toLowerCase().replace(/[\W_]/g,'');
  const length = str.length;
  if (length <= 1){
    return true;
  } else if (str.charAt(0) !== str.slice(-1)){
    return false;
  } else{
    return isPalindrome4(str.substring(1,length-1));
  }
}


console.log(isPalindrome1("A man, a plan, a canal. Panama.")); //=> true
console.log(isPalindrome2("madam  # ")) //=> true // only alnum for consideration
console.log(isPalindrome3("table")) //=> false
console.log(isPalindrome4("malayalam")) //=> true

For more ways

Multiple ways to check palindromes

Weird solution to test your skill

1

I believe this approach is much more readable and straightforward.

Array.from(str).every((char,index)=>char===str[(str.length-(index+1))]);
Aravinda Meewalaarachchi
  • 2,551
  • 1
  • 27
  • 24
0
function palindrome(str) {
// Good luck!
//convert the string into lowerCase.
 str = str.toLowerCase();
//this line remove all non=alphanumeric characters.
 strAlphaNum = str.replace(/[^a-z0-9]/g,"");
//this line create an array of the strAlphaNum string.
 strArray = strAlphaNum.split("");
//this line reverse the array
 strReversed = strArray.reverse();
//this line join the reversed array to make a string whithout space.
 strRevJoin = strReversed.join("");
//this condition check if the given string is a palindrome.
 if (strAlphaNum === strRevJoin){
 return true;}    
 else {return false;}
 }
Manassé
  • 991
  • 1
  • 7
  • 6
0
<script>
    function checkForPally() {
        var input = document.getElementById("inputTable").value;
        var input = input.replace(/\s/g, ''); 
        var arrayInput = input.split(); 
        var inputReversed = arrayInput.reverse();
        var stringInputReversed = inputReversed.join("");

        if (input == stringInputReversed) {
            check.value = "The word you enter is a palindrome"
        }
        if (input != stringInputReversed) {
            check.value = "The word you entered is not a palindrome"
        }
    }
</script>

You first use the getElement tag to set the initial variable of the palindrome. Seeing as a palindrome can be multiple words you use the regex entry to remove the whitespaces. You then use the split function to convert the string into an array.

Next up, you use the reverse method to reverse the array when this is done you join the reversed array back into a string. Lastly, you just use a very basic if statement to check for equality, if the reversed value is equall to the initial variable you have yourself a palindrome.

Neil Meyer
  • 473
  • 4
  • 15
0

This version allows special characters like "ñ" or "àèìòù" that in other answers doesn`t resolve it:

function palindromeUnicode(s)
{
     var sc = decodeURIComponent(escape(s));
     return sc === Array.from(sc).reverse().join('')
}
console.log(palindromeUnicode('áñitalavalatiñá')); //true
AntonioAvp
  • 1,033
  • 1
  • 7
  • 3
  • Note to future readers: `escape` is effectively deprecated and may be removed from the ECMAScript standard at a later date. – Heretic Monkey Nov 17 '19 at 01:19
0

Nice answers here. Here is another approach.

    function checkPalindrom(palindrom){
      var len = palindrom.length; //get length of the word
      var pos = len-1;      //get index of the last character
      var median  = len/2  // get median character
      if(len <= 1){
         document.write("The word is a Palindrome");
      }else{
         for(var i = 0; i < median+1; i++){
           if(palindrom.charAt(i) == palindrom.charAt(pos-i)){
             document.write("The word is a Palindrome")
           }
         }
         document.write("The word is not a Palindrome")
      }       

      checkPalindrom('wordthatwillbechecked');
Edgar256
  • 702
  • 9
  • 13
0

recursion only index compare:

const isPalindrome = (str, start = 0, end = str.length - 1) => {
    if (start >= end) {
        return true;
    }

    if (str[start] === str[end]) {
        return isPalindrome(str, start + 1, end - 1);
    }

    return false;
};

Adidi
  • 5,097
  • 4
  • 23
  • 30
0

A palindrome check can be done in Time Complexity O(n/2) with no Extra Space and Space Complexity O(1), by having left and right index pointers and move them towards the center. We don't need to create an extra array or list to loop through a string.


/*  
Check for planindrome
@string - input
@left - start index of string/input
@right - last index of string/input (which we can get from string.length - 1)
*/

function isPlaindrome(string, left, right) {
    while(left < right) {
        if(string[left] !== string[right]) {
            return false;
        };
        left++;
        right--;
    };

    return true;
};

console.log('abc =>', isPlaindrome('abc', 0, 'abc'.length - 1));
console.log('racecar => ', isPlaindrome('racecar', 0, 'racecar'.length - 1));
console.log('abba => ', isPlaindrome('abba', 0, 'abba'.length - 1));
console.log('xyzzyx => ', isPlaindrome('xyzzyx', 0, 'xyzzyx'.length - 1));


You can easily modify the function based on edge cases for string empty or string to lowercase to ignore caps situation.

Siddharth Sunchu
  • 866
  • 10
  • 13
0

The fastest for me using JSON.stringify instead of .join('')

function isPalindrome(s: string): boolean {
  s = s.replace(/[^a-zA-Z0-9]+/g, "").toLowerCase();
  const arrOfChars = s.split("");
  const reversed = [...arrOfChars].reverse();
  return JSON.stringify(reversed) === JSON.stringify(arrOfChars);
}
radzserg
  • 1,258
  • 1
  • 13
  • 22
0

O(1) space and O(n) speed

function isPalindrome(s, left = 0, right = s.length - 1) {
    while(left < right) {        
        if(s[left++] !== s[right--])
            return false;
    }

    return true;
}
Dennis Liger
  • 1,488
  • 2
  • 13
  • 28
-1

Palindrome is a string, which when read in both forward and backward way is same. Example: Example: madam, lol, pop, radar etc.

Simple Logic

//Sample string
  let str1 = "radar";
//breaking into a char array and sort
  let str1Arr = str1.split("").sort();//a,a,d,r,r
  let str2Arr = str1.split("").reverse().sort();//a,a,d,r,r
//now join both string separately and compare, if both are same then it is pelindrome     
  if(str1Arr.join("") == str2Arr.join(""))
  {
       console.log("Palindrome"); 
  }
  else{
       console.log("Not Palindrome"); 
  }