43

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad is not.

Thank you in advance.

nanobash
  • 5,419
  • 7
  • 38
  • 56
edgar7
  • 523
  • 2
  • 5
  • 7
  • 27
    usually objective of asking someone to write a function that detects a palindrome is to teach them programming. If you get someone else to do it, you're not learning anything. – Ben Mar 01 '14 at 07:31
  • 1
    This was already asked and answered a few times http://stackoverflow.com/a/20662606/437019 – Yossi Shasho Mar 05 '14 at 12:52

66 Answers66

68
function palindrome(str) {

    var len = str.length;
    var mid = Math.floor(len/2);

    for ( var i = 0; i < mid; i++ ) {
        if (str[i] !== str[len - 1 - i]) {
            return false;
        }
    }

    return true;
}

palindrome will return if specified word is palindrome, based on boolean value (true/false)

UPDATE:

I opened bounty on this question due to performance and I've done research and here are the results:

If we are dealing with very large amount of data like

var abc = "asdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfd";

for ( var i = 0; i < 10; i++ ) {
    abc += abc;  // making string even more larger
}

function reverse(s) { // using this method for second half of string to be embedded
    return s.split("").reverse().join("");
}

abc += reverse(abc); // adding second half string to make string true palindrome

In this example palindrome is True, just to note

Posted palindrome function gives us time from 180 to 210 Milliseconds (in current example), and the function posted below with string == string.split('').reverse().join('') method gives us 980 to 1010 Milliseconds.

Machine Details:

System: Ubuntu 13.10 OS Type: 32 Bit RAM: 2 Gb CPU: 3.4 Ghz*2 Browser: Firefox 27.0.1

Community
  • 1
  • 1
nanobash
  • 5,419
  • 7
  • 38
  • 56
  • 2
    Also note that in your first example you only need to traverse _half_ the string length. – MrWhite Mar 05 '14 at 17:26
  • 2
    @crypticous No, he meant your palindrome function is doing redundant comparisons for half the time; After comparing the first `str.length/2` characters to the last `str.length/2` characters, you already know if the string is a palindrome, since you've compared the first half to the last half. That is, you should divide `str.length` by two to get exactly the same result but twice as fast. – Aleksi Torhamo Mar 11 '14 at 21:39
  • @AleksiTorhamo I know what you mean, though I've counted time after whole string was successfully defined. I mean I counted time directly when started checking with `palindrome` function – nanobash Mar 11 '14 at 21:48
  • you might store the half in another variable to avoid calculate it every iteration `var half = Math.floor(len/2);` then in the for `for (var i = 0; i < half; i++) ` – Isaac Zepeda Mar 07 '15 at 19:34
  • So far as I can tell, `charCodeAt(n)` is always faster. See http://jsfiddle.net/7q1jo31e/2/, per my answer earlier http://stackoverflow.com/a/22343688/1888292 – tiffon Aug 14 '15 at 07:36
  • yah simpler more readable, is better AND faster -> https://jsfiddle.net/w5akpbv4/1/ i had an interview question and they challenged me to do it with AND/OR and recursion but its still slower than yours :) – King Friday Feb 04 '16 at 17:01
  • What if you split the strings into 2 with equal lengths, perform reverse on one, join and match with first string! That should be both readable and faster than splitting the complete string, reversing and rejoining. – Swanidhi Apr 06 '16 at 07:50
  • Genuinely asking: why do you need Math.floor in this? Under what situation would the length of a string not return a whole number? – Kyle Vassella Feb 16 '17 at 03:33
  • @KyleVassella, this might be pertaining to odd strings like 'aba' – NightEye Jan 25 '22 at 21:25
20

Try this:

var isPalindrome = function (string) {
    if (string == string.split('').reverse().join('')) {
        alert(string + ' is palindrome.');
    }
    else {
        alert(string + ' is not palindrome.');
    }
}

document.getElementById('form_id').onsubmit = function() {
   isPalindrome(document.getElementById('your_input').value);
}

So this script alerts the result, is it palindrome or not. You need to change the your_id with your input id and form_id with your form id to get this work.

Demo!

aksu
  • 5,221
  • 5
  • 24
  • 39
  • Just wondering if there might be potential problems with the string reversal method used here, due to JavaScript's internal character encoding? I doubt this would be a problem with English palindromes, however, it might be more of a problem in other languages. Just something to be aware of. stackoverflow.com/a/16776621/369434 – MrWhite Mar 05 '14 at 13:42
  • You are right, but I think the OP didn't need compatibility for i.e non-letters like symbols or something. As he pointed out the example "noon". Why even you would like to have support for symbols? – aksu Mar 05 '14 at 14:50
  • I wasn't necessarily thinking of generic "symbols", but of accented letters (eg. á, é, í, ó, ú, ü, ñ, etc.) and other non-latin alphabets - whether they would be a problem or not I don't know. But yes, only English examples were given. – MrWhite Mar 05 '14 at 15:04
  • 1
    While this solution is simple/beautiful, but with larger sets of data wouldn't the combination of `==` and `.reverse()` be slower than just traversing half the string length? – theGreenCabbage Mar 11 '14 at 21:53
  • Compares s == s^R instead of looking at cases s = uv and s = uav with same length halves u and v and then comparing u == v^R. – mvw Mar 12 '14 at 11:33
  • Nowhere in the OP's post is mentioned about performance. My script only a bit slow with large amount of data. The slowness doesn't show when checking if i.e word *noon* is a palindrome. – aksu Mar 12 '14 at 13:10
  • @aksu I think my answer don't suffer this performance issue with large amount of data. Here you do a lot of useless operations. Simple code but with operation overhead. – piacente.cristian Mar 12 '14 at 13:43
  • Just to Note... `Was it a cat I saw` `alert`s NOT a palindrome – ErickBest Sep 01 '14 at 12:48
16

Use something like this

function isPalindrome(s) {
    return s === s.split("").reverse().join("") ? true : false;
}

alert(isPalindrome("noon"));

alternatively the above code can be optimized as [updated after rightfold's comment]

function isPalindrome(s) {
    return s === s.split("").reverse().join("");
}

alert(isPalindrome("malayalam")); 
alert(isPalindrome("english")); 
kiranvj
  • 32,342
  • 7
  • 71
  • 76
  • 1
    @rightfold I would say it's more verbose. You can instantly see that it'll be returning a boolean. – James Mar 11 '14 at 23:00
  • The comparison s == s^R suffers from the double effort as well, as in case of a palindrome s = uu^R it compares uu^R with (uu^R)^R = (u^R)^Ru^R = u^Ru, where it would suffice to split at the middle and compare u with u^R instead. – mvw Mar 12 '14 at 11:22
9

Faster Way:

-Compute half the way in loop.

-Store length of the word in a variable instead of calculating every time.

EDIT: Store word length/2 in a temporary variable as not to calculate every time in the loop as pointed out by (mvw) .

function isPalindrome(word){
   var i,wLength = word.length-1,wLengthToCompare = wLength/2;

   for (i = 0; i <= wLengthToCompare ; i++) {
     if (word.charAt(i) != word.charAt(wLength-i)) {
        return false;
     }
   }
   return true;
} 
Sai
  • 2,068
  • 19
  • 24
  • 4
    I am pretty sure that modern JS engines can optimize out the `.length` access – Bartek Banachewicz Mar 05 '14 at 12:52
  • +1 for the traversing half the original string length (other answers seem to have missed this for some reason). – MrWhite Mar 05 '14 at 13:08
  • @BartekBanachewicz You are correct that the 'length' property is not always calculated and thus does not cost performance on some browsers. However, on some browsers, caching to a variable is faster than accessing the 'length' property in a loop. – Sai Mar 05 '14 at 15:27
  • @Sai Then at least it shouldn't be stated that it's ultimately faster, but I see you've already done the edit. – Bartek Banachewicz Mar 05 '14 at 15:29
  • But you recalculate wLength/2 + 1 and wLength-1 at every iteration of the loop. – mvw Mar 12 '14 at 11:25
7

Look at this:

function isPalindrome(word){
    if(word==null || word.length==0){
        // up to you if you want true or false here, don't comment saying you 
        // would put true, I put this check here because of 
        // the following i < Math.ceil(word.length/2) && i< word.length
        return false;
    }
    var lastIndex=Math.ceil(word.length/2);
    for (var i = 0; i < lastIndex  && i< word.length; i++) {
        if (word[i] != word[word.length-1-i]) {
            return false;
        }
     }
     return true;
} 

Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!

Since the string is an array of char no need to use charAt functions!!!

Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome

7

Let us start from the recursive definition of a palindrome:

  1. The empty string '' is a palindrome
  2. The string consisting of the character c, thus 'c', is a palindrome
  3. If the string s is a palindrome, then the string 'c' + s + 'c' for some character c is a palindrome

This definition can be coded straight into JavaScript:

function isPalindrome(s) {
  var len = s.length;
  // definition clauses 1. and 2.
  if (len < 2) {
    return true;
  }
  // note: len >= 2
  // definition clause 3.
  if (s[0] != s[len - 1]) {
    return false;
  }
  // note: string is of form s = 'a' + t + 'a'
  // note: s.length >= 2 implies t.length >= 0
  var t = s.substr(1, len - 2);
  return isPalindrome(t);
}

Here is some additional test code for MongoDB's mongo JavaScript shell, in a web browser with debugger replace print() with console.log()

function test(s) {
  print('isPalindrome(' + s + '): ' + isPalindrome(s));
}

test('');
test('a');
test('ab');
test('aa');
test('aab');
test('aba');
test('aaa');
test('abaa');
test('neilarmstronggnortsmralien');
test('neilarmstrongxgnortsmralien');
test('neilarmstrongxsortsmralien');

I got this output:

$ mongo palindrome.js
MongoDB shell version: 2.4.8
connecting to: test
isPalindrome(): true
isPalindrome(a): true
isPalindrome(ab): false
isPalindrome(aa): true
isPalindrome(aab): false
isPalindrome(aba): true
isPalindrome(aaa): true
isPalindrome(abaa): false
isPalindrome(neilarmstronggnortsmralien): true
isPalindrome(neilarmstrongxgnortsmralien): true
isPalindrome(neilarmstrongxsortsmralien): false

An iterative solution is:

function isPalindrome(s) {
  var len = s.length;
  if (len < 2) {
    return true;
  }
  var i = 0;
  var j = len - 1;
  while (i < j) {
    if (s[i] != s[j]) {
      return false;
    }
    i += 1;
    j -= 1;
  }
  return true;
}
mvw
  • 5,075
  • 1
  • 28
  • 34
4

Best Way to check string is palindrome with more criteria like case and special characters...

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

You can test it with following words and strings and gives you more specific result.
1. bob
2. Doc, note, I dissent. A fast never prevents a fatness. I diet on cod

For strings it ignores special characters and convert string to lower case.

kiranvj
  • 32,342
  • 7
  • 71
  • 76
Mihir Vadalia
  • 93
  • 1
  • 3
4

Taking a stab at this. Kind of hard to measure performance, though.

function palin(word) {
    var i = 0,
        len = word.length - 1,
        max = word.length / 2 | 0;

    while (i < max) {
        if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
            return false;
        }
        i += 1;
    }
    return true;
}

My thinking is to use charCodeAt() instead charAt() with the hope that allocating a Number instead of a String will have better perf because Strings are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'), the middle character is always ok.

Community
  • 1
  • 1
tiffon
  • 5,040
  • 25
  • 34
3

String.prototype.isPalindrome = function isPalindrome() {

    const cleanString = this.toLowerCase().replace(/\s+/g, '');
    const cleanStringRevers = cleanString.split("").reverse().join("");

    return cleanString === cleanStringRevers;
}

let nonPalindrome = 'not a palindrome';
let palindrome = 'sugus';

console.log(nonPalindrome.isPalindrome())

console.log(palindrome.isPalindrome())
Mario Perez
  • 2,777
  • 1
  • 12
  • 21
sedoy113
  • 31
  • 2
2

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
  • 1
    this really needs to be the top answer. all the others are using shortcut methods, which not only DONT demonstrate how you think algorithmically but are also very unperformant! – feihcsim Dec 08 '17 at 19:53
  • 1
    @feihcsim, coming back to this answer, I noticed we could take this a step further. If we want to, we could even eliminate the 2nd loop (and the use of `mid`) and set `j` equal to `s.length - i` while iterating over the entire array (`break`ing at `i >= j`) (not that it effects our time complexity). This is how I, personally, write it in tests now days, but that is more of a matter of what is more readable. It also seems that I mentioned *returning false by default* but it doesn't look like I am doing that here. Thank you for the kudos. – Cody Jan 18 '18 at 17:07
2

This function will remove all non-alphanumeric characters (punctuation, spaces, and symbols) and turn everything lower case in order to check for palindromes.

function palindrome(str){

    var re = /[^A-Za-z0-9]/g;
    str = str.toLowerCase().replace(re, '');
    return str == str.split('').reverse().join('') ? true : false;

}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
viveknaskar
  • 2,136
  • 1
  • 20
  • 35
2

Here's a one-liner without using String.reverse,

const isPal = str => [...new Array(strLen = str.length)]
  .reduce((acc, s, i) => acc + str[strLen - (i + 1)], '') === str;
2

Here is an optimal and robust solution for checking string palindrome using ES6 features.

const str="madam"
var result=[...str].reduceRight((c,v)=>((c+v)))==str?"Palindrome":"Not Palindrome";
console.log(result);
2

Try this

isPalindrome = (string) => {
    if (string === string.split('').reverse().join('')) {
        console.log('is palindrome');
    }
    else {
        console.log('is not palindrome');
    }
}

isPalindrome(string)
Neelesh Shetty
  • 389
  • 2
  • 7
1
function palindrome(str) {
    var lenMinusOne = str.length - 1;
    var halfLen = Math.floor(str.length / 2);

    for (var i = 0; i < halfLen; ++i) {
        if (str[i] != str[lenMinusOne - i]) {
            return false;
        }
    }
    return true;
}

Optimized for half string parsing and for constant value variables.

neural5torm
  • 773
  • 1
  • 9
  • 21
  • For odd length strings, e.g. str = 'foo', your comparsion looks like "i < 1.5" which involves floats. I wonder if that impacts js engines. And you can avoid calculation arbitrary differences "lenMinusOne - i" by using increments and decrements. Not sure here too, if this would impact modern js engines. – mvw Mar 12 '14 at 12:39
  • @mvw It will take floor value. – Karthik Surianarayanan Mar 12 '14 at 12:44
  • No you're right, it's not rounded like in C, my bad. Still, this algorithm is twice as fast as the accepted answer's on my setup. – neural5torm Mar 12 '14 at 12:44
  • 1
    Many answers here iterate over the full string instead of the half or do the mirror test with the full string instead of halves. The hive mind of the crowd has not realized this yet. :-) – mvw Mar 12 '14 at 12:51
  • The point of my answer is to make difference with `reverse` function palindrome, the algorithm remains the same in your answer's case. Anyways good job :) – nanobash Mar 12 '14 at 12:54
  • I understand, but since your bounty was about performance efficiency, I thought cutting the computation in half was not so bad an improvement. ;) – neural5torm Mar 12 '14 at 12:57
  • All the answers on here are the same despite mine and the one with `reverse`, I didn't divide string length into 2 purposely, instead I make it bigger to make difference between times with marked algorithms . – nanobash Mar 12 '14 at 12:58
1

I think following function with time complexity of o(log n) will be better.

    function palindrom(s){
    s = s.toString();
    var f = true; l = s.length/2, len = s.length -1;
    for(var i=0; i < l; i++){
            if(s[i] != s[len - i]){
                    f = false; 
                    break;
            }
    }
    return f;

    }

console.log(palindrom(12321));

Kashyap
  • 107
  • 1
  • 5
1

Here's another way of doing it:

function isPalin(str) {
  str = str.replace(/\W/g,'').toLowerCase();
  return(str==str.split('').reverse().join(''));
}
ssube
  • 47,010
  • 7
  • 103
  • 140
tuya senff
  • 71
  • 4
1

Below code tells how to get a string from textBox and tell you whether it is a palindrome are not & displays your answer in another textbox

<html>
<head>
<meta charset="UTF-8"/>
<link rel="stylesheet" href=""/>

</head>  
<body>   
<h1>1234</h1>
<div id="demo">Example</div>
<a  accessKey="x" href="http://www.google.com" id="com" >GooGle</a>
<h1 id="tar">"This is a Example Text..."</h1>
Number1 : <input type="text" name="txtname" id="numb"/>
Number2 : <input type="text" name="txtname2" id="numb2"/>
Number2 : <input type="text" name="txtname3" id="numb3" />
<button type="submit"  id="sum" onclick="myfun()" >count</button>
<button type="button"  id="so2" onclick="div()" >counnt</button><br/><br/>
<ol>
<li>water</li>
<li>Mazaa</li>
</ol><br/><br/>
<button onclick="myfun()">TryMe</button>
    <script>
    function myfun(){
    var pass = document.getElementById("numb").value;
    var rev = pass.split("").reverse().join("");
    var text = document.getElementById("numb3");
    text.value = rev;
    if(pass === rev){
    alert(pass + " is a Palindrome");
    }else{
    alert(pass + " is Not a Palindrome")
    }
    }
    </script>
</body>  
</html>  
kumar
  • 21
  • 2
1

25x faster + recursive + non-branching + terse

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

See my complete explanation here.

Community
  • 1
  • 1
King Friday
  • 25,132
  • 12
  • 90
  • 84
1

The code is concise quick fast and understandable.

TL;DR

Explanation :

Here isPalindrome function accepts a str parameter which is typeof string.

  1. If the length of the str param is less than or equal to one it simply returns "false".
  2. If the above case is false then it moves on to the second if statement and checks that if the character at 0 position of the string is same as character at the last place. It does an inequality test between the both.

    str.charAt(0)  // gives us the value of character in string at position 0
    str.slice(-1)  // gives us the value of last character in the string.
    

If the inequality result is true then it goes ahead and returns false.

  1. If result from the previous statement is false then it recursively calls the isPalindrome(str) function over and over again until the final result.

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


document.getElementById('submit').addEventListener('click',function(){
 var str = prompt('whats the string?');
 alert(isPalindrome(str))
});

document.getElementById('ispdrm').onsubmit = function(){alert(isPalindrome(document.getElementById('inputTxt').value));
}
<!DOCTYPE html>
<html>
<body>
<form id='ispdrm'><input type="text" id="inputTxt"></form>

<button id="submit">Click me</button>
</body>
</html>
kRiZ
  • 2,320
  • 4
  • 28
  • 39
Sagar Munjal
  • 762
  • 11
  • 12
1
    function palindrome(str) {
        var re = /[^A-Za-z0-9]/g;
        str = str.toLowerCase().replace(re, '');
        var len = str.length;
        for (var i = 0; i < len/2; i++) {
            if (str[i] !== str[len - 1 - i]) {
                return false;
            }
        }
        return true;
    }
1

Or you could do it like this.

var palindrome = word => word == word.split('').reverse().join('')
Alex Cory
  • 10,635
  • 10
  • 52
  • 62
1

How about this one?

function pall (word) {

    var lowerCWord = word.toLowerCase();
    var rev = lowerCWord.split('').reverse().join('');

    return rev.startsWith(lowerCWord);
    }

pall('Madam');
TheBilTheory
  • 408
  • 2
  • 12
1

str1 is the original string with deleted non-alphanumeric characters and spaces and str2 is the original string reversed.

function palindrome(str) {

  var str1 = str.toLowerCase().replace(/\s/g, '').replace(
    /[^a-zA-Z 0-9]/gi, "");

  var str2 = str.toLowerCase().replace(/\s/g, '').replace(
    /[^a-zA-Z 0-9]/gi, "").split("").reverse().join("");


  if (str1 === str2) {
    return true;
  }
  return false;
}

palindrome("almostomla");
4b0
  • 21,981
  • 30
  • 95
  • 142
1
function isPalindrome(s) {
    return s == reverseString(s);
}

console.log((isPalindrome("abcba")));

function reverseString(str){
    let finalStr=""
    for(let i=str.length-1;i>=0;i--){
        finalStr += str[i]
    }
    return finalStr
}
Shashwat Gupta
  • 5,071
  • 41
  • 33
1

Frist I valid this word with converting lowercase and removing whitespace and then compare with reverse word within parameter word.

function isPalindrome(input) {
    const toValid = input.trim("").toLowerCase();
    const reverseWord = toValid.split("").reverse().join("");
    return reverseWord == input.toLowerCase().trim() ? true : false;
}
isPalindrome("    madam ");
//true
1

This answer is easy to read and I tried to explain by using comment. Check the code below for How to write Palindrome in JavaScript. Step 1: Remove all non-alphanumeric characters (punctuation, spaces and symbols) from Argument string 'str' using replace() and then convert in to lowercase using toLowerCase(). Step 2: Now make string reverse. first split the string into the array using split() then reverse the array using reverse() then make the string by joining array elements using join() . Step 3: Find the first character of nonAlphaNumeric string using charAt(0). Step 4: Find the Last character of nonAlphaNumeric string using charAt(length of nonAlphaNumeric string - 1). Step 5: Use If condition to chack nonAlphaNumeric string and reverse string is same or not. Step 6: Use another If condition to chack first character of nonAlphaNumeric string is same to Last character of nonAlphaNumeric string.

function palindrome(str) {
  var nonAlphaNumericStr = str.replace(/[^0-9A-Za-z]/g, "").toLowerCase(); // output - e1y1e
 
  var reverseStr = nonAlphaNumericStr.split("").reverse().join(""); // output - e1y1e
  
  var firstChar = nonAlphaNumericStr.charAt(0); // output - e
  
  var lastChar = nonAlphaNumericStr.charAt(nonAlphaNumericStr.length - 1); // output - e
  
  if(nonAlphaNumericStr === reverseStr) {
    
    if(firstChar === lastChar) {
      return `String is Palindrome`; 
    }
  }
  return `String is not Palindrome`; 
}
console.log(palindrome("_eye"));

Chetan Nada
  • 86
  • 1
  • 4
1

function check(txt)

{
  for (var i = txt.length; i >= 0; i--)

    if (txt[i] !== txt[txt.length - 1 - i])

      return console.log('not palidrome');
  return console.log(' palidrome');
}

check('madam');
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
0

Note: This is case sensitive

function palindrome(word)
{
    for(var i=0;i<word.length/2;i++)
        if(word.charAt(i)!=word.charAt(word.length-(i+1)))
            return word+" is Not a Palindrome";
    return word+" is Palindrome";
}

Here is the fiddle: http://jsfiddle.net/eJx4v/

0

I am not sure how this JSPerf check the code performance. I just tried to reverse the string & check the values. Please comment about the Pros & Cons of this method.

function palindrome(str) {
    var re = str.split(''),
        reArr = re.slice(0).reverse();

    for (a = 0; a < re.length; a++) {
        if (re[a] == reArr[a]) {
            return false;
        } else {
            return true;
        }
    }
}

JS Perf test

SVS
  • 4,245
  • 1
  • 23
  • 28
0
function palindrome(str){
    for (var i = 0; i <= str.length; i++){ 
        if  (str[i] !== str[str.length - 1 - i]) {
            return "The string is not a palindrome";
        }
    }
return "The string IS a palindrome"
}

palindrome("abcdcba"); //"The string IS a palindrome"
palindrome("abcdcb"); //"The string is not a palindrome";

If you console.log this line: console.log(str[i] + " and " + str[str.length - 1 - i]), before the if statement, you'll see what (str[str.length - 1 - i]) is. I think this is the most confusing part but you'll get it easily when you check it out on your console.

Andrew
  • 4,953
  • 15
  • 40
  • 58
Camilo Ordonez
  • 129
  • 1
  • 11
0

All these loops! How about some functional goodness :) May run in to tail call issues on old/current js engines, solved in ES6

function isPalendrome(str){
    var valid = false;
    if(str.length < 2 ) return true;
    function even(i,ii){
        str[i]===str[ii] ? ((i+1 !== ii) ? even(i+1,ii-1) : valid = true) : null
    }
    function odd(i, ii){
        str[i]===str[ii] ? ((i !== ii) ? odd(i+1,ii-1) : valid = true) : null
    }
    if(str.length % 2){
        return odd(0,str.length-1),valid;
    }else{
        return even(0,str.length-1),valid;
    }
}

To test your call stack run this code, you will be able to parse strings double the call stack size

function checkStackSize(){
    var runs = 70000;
    var max_process = 1;
    var max = 0;
    function recurse_me() {
        max_process++;
        if(max_process === runs) return;
        max = max_process;
        try {
            recurse_me()
        } catch(e) {
            max =  max_process;
        }
    }
    recurse_me()
    console.log(max);
}

Due to the symmetrical nature of the problem you could chunk the string from the outside in and process the chunks that are within call stack limits.

by that I mean if the palindromes length is 1000. You could join 0-250 and 750-1000 and join 250-499 with 500-749. You can then pass each chunk in to the function. The advantage to this is you could run the process in parallel using web workers or threads for very large data sets.

elev8ed
  • 183
  • 1
  • 7
0
function palindrome(str) {    
    var testString = str.toLowerCase();


    var expression = /[a-z0-9\^s]/gi;
    if (testString.match(expression).reverse().join("") == testString.match(expression).join("")) {
        return true;
    } else {
        return false;
    }
}
Undo
  • 25,519
  • 37
  • 106
  • 129
Cis Dev
  • 1
  • 2
0

You could also do something like this :

function isPalindrome(str) {
var newStr = '';

for(var i = str.length - 1; i >=0; i--) {
    newStr += str[i];
}

if(newStr == str) {
    return true;
    return newStr;
} else {
    return false;
    return newStr;
}
}
FNunez
  • 98
  • 2
  • 12
  • You could improve your answer by pointing out its advantages over other proposed answers, the algorithm itself, the double returns, etc. – dakab Jan 30 '16 at 16:22
0

ES6 way of doing it. Notice that I take advantage of the array method reduceRight to reverse a string (you can use array methods on strings if you give the string as context, as low level - strings are arrays of chars). No it is not as performant as other solutions, but didn't see any answer that came it it using es6 or higher order functions so figured I'd throw this one out there.

const palindrome = str => {
  const middle = str.length/2;
  const left = str.slice(0, middle)
  const right = Array.prototype.reduceRight.call(str.slice(Math.round(middle)), (str, char) => str + char, '')
  return left === right;
}
0

To avoid errors with special characters use this function below

function palindrome(str){
  var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();
  var checkPalindrome = removeChar.split('').reverse().join('');
  if(removeChar === checkPalindrome){
     return true;
  }else{
    return false;
  }
}
  • You might want to add some example of a case that you function handles better than other solutions :) – Fge Jul 25 '16 at 22:47
  • try running other solutions with this string "A man, a plan, a canal. Panama", "My age is 0, 0 si ega ym." and this "0_0 (: /-\ :) 0-0". you notice the kind of errors i am talking about – paradise-ekpereta Jul 25 '16 at 23:17
0

This tests each end of the string going outside in, returning false as soon as a lack of symmetry is detected. For words with an odd number of letters, the center letter is not tested.

function isPalindrome(word){
    var head = 0;
    var tail = word.length - 1;

    while (head < tail) {
        if (word.charAt(head) !== word.charAt(tail)){
            return false
        } else {
            head ++;
            tail --;
        }
    };
    return true;
};
John Escobedo
  • 128
  • 1
  • 6
0
function palindrome(s) {
  var re = /[\W_]/g;
  var lowRegStr = s.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  return reverseStr === lowRegStr;
}
0

For better performance you can also use this one

function palindrome(str) {
 str = str.split("");
 var i = str.length;
 var check = "Yes"
 if (i > 1) {
    for (var j = 0; j < i / 2; j++) {
        if (str[j] != str[i - 1 - j]) {
            check = "NO";
            break;
           }
        }
        console.log(check);
    } else {
    console.log("YES");
  }
}
Himanshu Teotia
  • 2,126
  • 1
  • 27
  • 38
0

A simple one line code to check whether the string is palindrome or not:

function palindrome (str) {

  return str === str.split("").reverse().join("");

}
<!-- Change the argument to check for other strings -->
<button type="button" onclick="alert(palindrome('naman'));">Click Me<utton>

The above function will return true if the string is palindrome. Else, it will return false.

Akash Kriplani
  • 162
  • 1
  • 12
0

My short solution, with the length of 66 characters. The result: true or false.

function isPalindrome(s) {
  s=s.toLowerCase().match(/\w/g);
  return s.join()==s.reverse().join();
}
0

I think this implementation covers pretty much every case. I hope it's useful to someone:

function isPalindrome(word){
    if(typeof word === 'undefined' || word === null){
        console.log("argument is undefined");
        return;
    }

    if(typeof word === 'string'){

       word = word.replace(/\s/gi,"");

     if(word.length < 1){
        console.log("wrong argument");
        return;
      }

      if(word.length === 1){
        console.log("It's palindrome!");
        return;
      }

      for(var i=0;i<Math.floor(word.length/2);i++){

        if(word[i] !== word[word.length - 1 - i]){
          console.log("It's not palindrome");
          return;
        }
      }
      console.log("It's palindrome");

    }else{

       console.log("argument must be a string");

    }

}

And then you can try with these cases:

isPalindrome("nurses run");
isPalindrome("abcdcba");
isPalindrome("hello world");
isPalindrome("  ");
isPalindrome(" ");
isPalindrome("");
isPalindrome(null);
isPalindrome();
isPalindrome(100);
isPalindrome({"name":"John"});
Gustavo
  • 33
  • 1
  • 7
0
function Palindrome(str) {
  let forwardStr = str.toLowerCase().replace(/[\W_]/g, '');
  let reversedStr = forwardStr.split('').reverse().join();

  return forwardStr === reversedStr;
}
console.log(Palindrome('madam'));
Mike
  • 458
  • 4
  • 13
  • 1
    While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – peacetype Mar 21 '18 at 00:23
0

    function reversName(name){
            return name
                  .split('')
                  .reverse()
                  .join('') === name ;
    };
    console.log(reversName('suus'));
    console.log(reversName('suusss'));
sudheer nunna
  • 1,659
  • 15
  • 17
0

/* Following function does the below mentioned task.

 1. Fetch all the substrings of a given string. 
 2. Find which of the substrings are palindromes.
 3. Find the longest palindrome.
 4. Find if the longest palindrome is a lucky palindrome.

  */

function SubstringMnipulations(S) {
    let Str = S.toString(); 
    let AllSubStrs = splitSubstrings(Str);
    let Pelindromes = arePelindrome(AllSubStrs);
    let LongestPelindrome = getLongestString(Pelindromes);
    let isPrimeVar = isPrime(LongestPelindrome);
    return {
      "possibleSubstrings": AllSubStrs,
      "pelindromes": Pelindromes,
      "longestPelindrome": LongestPelindrome,
      "isLuckyPelindrome": isPrimeVar
    };
  }

function splitSubstrings(Str) {
  let StrLength = Str.length;
  let maxIndex = StrLength;
  let AllSubStrs = [];
  for(var index = 0; index < maxIndex; index++ ) {
    for(var innerIndex = 1; innerIndex <= maxIndex-index; innerIndex++) {
      AllSubStrs.push(Str.substring(index, (index+innerIndex)));
    }
  }
  return AllSubStrs;
}

function arePelindrome(StrArr) {
  let pelindrome = [];
  for(i=0; i<StrArr.length;i++) {
    if(isPelindrome(StrArr[i])) {
      if(StrArr[i].length>1) {
        pelindrome.push(StrArr[i]);
      }
    }
  }

  return pelindrome;
}

function isPelindrome(Str) {
  let strLen = Str.length;
  let firstHalfIndex = 0;
  if(strLen==1) {
    return true;
  }

  let firstHalf = "";
  let secondHalf = "";

  if(strLen>1 && strLen%2==0) {
    firstHalfIndex = strLen/2;
    firstHalf = Str.substring(0, firstHalfIndex);
    secondHalf = Str.substring((firstHalfIndex), strLen);
  } else {
    firstHalfIndex = (strLen-1)/2;
    firstHalf = Str.substring(0, firstHalfIndex);
    secondHalf = Str.substring((1+firstHalfIndex), strLen);
  }

  secondHalf = reverseString(secondHalf);
  return firstHalf === secondHalf;
}

function reverseString(Str) {
  return Str.split("").reverse().join("");
}

function getLongestString(Str) {
  let lengthCount = [];
  for(i=0; i<Str.length;i++) {
    lengthCount.push(Str[i].length);
  }

  return Str[lengthCount.indexOf(Math.max(...lengthCount))];
}

function isPrime(Str) {
  let input = Str.length;
  let prime = true;
    for (let i = 2; i <= Math.sqrt(input); i++) {
        if (input % i == 0) {
            prime = false;
            break;
        }
    }
    return prime && (input > 1);
}
0

function palindrome(str) {
  var re = /[\W_]/g; // or var re = /[^A-Za-z0-9]/g;
  var lowRegStr = str.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join('');
  return reverseStr === lowRegStr;
}
console.log(palindrome("A nut for a jar of tuna"));
console.log(palindrome("Helo World"));
Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
iamsohel
  • 387
  • 3
  • 7
0

What i use:-

function isPalindrome(arg){
    for(let i=0;i<arg.length;i++){
        if(arg[i]!==arg[(arg.length-1)-i]) 
          return false;
    return true;
}}
Subhash Saini
  • 254
  • 4
  • 5
0

Here is a 1 line program to check if your string is a palindrome :-

((s) => `Is ${s} a palindrome ? \n Answer is :- ${s.split('').reverse().join('') == s}`)('bob')

Just modify the last parameter of this IIFE to check different inputs. This is perhaps the best solution.

0
function isPalindrome(str) {
  var isPalindrome = true;

  if(str.length === 2){
    return isPalindrome;
  }
  for(let i = 0, d = str.length - 1; i<(d-i); i++ )
  {
    if(str[i] !== str[d - i] ){
      return !isPalindrome
    }
  }
   return isPalindrome
  }
Faris
  • 91
  • 1
  • 5
0
function isPalindrome(word) {
    let strLen = word.length;
    word = word.toLocaleLowerCase();

    if (strLen === 0 || strLen === 1) {
        return true;
    }

    if (word[0] === word[strLen - 1])  {
        return isPalindrome(word.slice(1, strLen - 1) );
    }  

    return false;
}
Esom
  • 11
  • 1
0

Alternative solution for using Array.prototype.every()

function palindrome(str) {
  return str.split('').every((char, index) => {
     return char === str[str.length - index - 1];
  });
}
slymnozdmrc
  • 390
  • 2
  • 8
  • 20
0

You can try the following code with n/2 complexity

   palindrom(word)
   {
        let len = word.length

        let limit = len % 2 ? (len - 1)/2 : (len/2)

        for(let i=0; i < limit; i++)
        {
            if(word[i] != word[len-i-1])
            {
                alert('non a palindrom')
                return
            }
        }

        alert('palindrom')
        return;
   }

calling the function

palindrom('abba')

Saddam
  • 1,174
  • 7
  • 14
0
 var a = 121;
        var aNum = a.toString().split("");
        var b = aNum.slice(0).reverse();
        aNum = aNum.join("");
        b = b.join("");
     
      
      if(aNum==b){
          console.log("Its A Palindrome")
          

  }else{
      console.log("Its Not A Palindrome")
  }
  • Please add some explanation to your answer such that others can learn from it. – Nico Haase Oct 25 '21 at 06:42
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 25 '21 at 06:45
0
const isPalindrome = str => {
    
    // base case
    if(str.length === 1) return true;
    if(str.length === 2) return str[0] === str[1];

    if(str[0] === str[str.length - 1]) {
        return isPalindrome(str.slice(1, -1))
    }

    return false;
}

you can use recursion

base case

we have a base case (the simple case) if the string is one char we simply returns true.

if it has two chars we check if the first char is identical to the second and we return true if they are.

recursive case

if it is more than two chars we check if the first and last chars are identical or not if they are not we simply return false

but if they are identical so we now want to do the same thing with other chars so we call the same function with the same string but removing the first and last chars because we already know that they are identical and we keep going until we reach the base case.

hope this be useful

some tests

isPalindrome('p')    // true
isPalindrome('po')   // false
isPalindrome('pp')   // true
isPalindrome('pop')  //true
0
const isPalindrome = function (inputValue) {
const input = `${inputValue}`;

for (let char = 0; char < (input.length-1)/2; char++) {
    if (input[char] != input[input.length - 1 - char]) {
        return false;
    }
}

return true;
};

isPalindrome(123); // false
isPalindrome("aba"); // true
isPalindrome(121); // true
isPalindrome("abc"); // false

This code will work for both string and number type input

Ashita.gupta
  • 321
  • 3
  • 5
0

the easiest way that in my mind is using reduce

function palindrome(str) {
  let reversed = str.split('').reduce((acc, char) => char + acc, '');
  if (str === reversed) {
    return true;
  } else {
    return false;
  }
}

or maybe you like using every

function palindrome(str) {
  return str.split('').every((char, i) => {
    return char === str[str.length - i - 1];
  });
}
0
function palindrome(no) {

     let a = no.toString().split("");
    
     var b = [];
    for (var k = a.length - 1; k >= 0; k--) {
        b.push(a[k]);
    }
    var cc = null;
    for(var o in a) {
        if (a[o] === b[o]) {
            cc = true;
        } else {
            cc = false;
            break;
        }
    }
    if (cc) {
 console.log('it is palindrome');
    } else {
 console.log('it is not palindrome');
    }

}
palindrome(1)
  • It's cool to answer a question, but your answer should include more info than just a code block. – kelsny Feb 22 '22 at 00:54
0

What about this :

isPalindrome = (txt)=> [...txt].toString() === [...txt].reverse().toString();
isPalindrome('level');

isPalindrome = (txt)=> [...txt].toString() === [...txt].reverse().toString();
console.log(isPalindrome('level'))
Toxy
  • 696
  • 5
  • 9
0
  1. we can check that string is palindrome or not with just simple function

    public palindrome(str) {
        var lowRegStr = str.toLowerCase();
        var reverseStr = lowRegStr.split('').reverse().join(''); 
        return reverseStr === lowRegStr;
    }
    this.palindrome("123321");
    

you will get boolean value, true or false

Apurv Chaudhary
  • 1,672
  • 3
  • 30
  • 55
0

Below solution will ignore special characters and check whether the input is palindrome or not. If any interviewer asked this kind of question it may helpful

function palindrome(_val) {
var str = _val.toString();
str = str.toLowerCase();
str = str.replace(/[\W_]/g, '');
function palindrome(_val) {
var str = _val.toString();
str = str.toLowerCase();
str = str.replace(/[\W_]/g, '');
  function reverse(str1){
    var items = str1.split("");
    var length = items.length;
    var val="";
    for(var i=length-1;i>=0;i--){
      //console.log(items[i]);
      val=val+items[i];
    }
    return val;
  }

  function reverse1(str1){
    return str1.split("").reverse().join("");
  }
  var _res = reverse1(str);
  
  if(_res==str)
     return true;
  else
    return false;
}

var _res = palindrome("A man, a plan, a canal. Panama");
console.log(_res);
Mihir
  • 8,696
  • 18
  • 56
  • 87
0

you can try this without the reverse join and split method. pre-defined method with higher code complexity than develop by self

var result = "";
function reverseNumber(n) {
    // reverse the number via loop 
    for (var i = x.length - 1; i >= 0; i--) {
        result += n[i];
    }
    if(n===result){
        return "Palindrome"
    }
    else{
        return "Not Palindrome"
    }
}
var x = prompt("Enter a String : ");
console.log(reverseNumber(x))
sadiq shah
  • 11
  • 3
0

One of the easiest way is

Reverse the first string and check reversed string with second string, if it matches with First Reversed String it's Palindrome and if it's not then it's not Palindrome.

Let's understand by code:

const firstString = "madam";
const secondString = "MADAM";

function isPalindrome(firstString, secondString){
   // Reversing the first string by lowercasing the characters.
   const reverseString = firstString.toLowerCase().split("").reverse().join("");

   // Checking the reversed string matches with second string
   if(reverseString === secondString.toLowerCase()){
       return "Palindrome";
   } else {
       return "Not Palindrome";
   }
}

// Calling the function
console.log( isPalindrome(firstString, secondString) );

Hope it helps!

Shweta
  • 661
  • 6
  • 11
-1

not exactly javascript syntax, but this checker i wrote confirmed a 13,088-digit long string is palindrome on my 2018-laptop in 11 milliseconds :

time  mawk -v INP="${a}" ' 
    function _r2utl(_,__,___) {
        return ___<__?_r2utl(substr(_,\
        int(__/=___)+!!__),__%--___+__,\
         ___+___)_r2utl(substr(_,___++,\
                     __=int(__)),__,___)\
        :__<___?(_):substr((_)_,___,___) 
    }
    function rev2(_,__,___) {
        return ((___=length(_))<(__+=++__))\
                        ?_:_r2utl(_,___,__)
    }
    function is_pdrome(__,_,___) {
        if (__=="") { return __^__ }
        ___=_^=_;___=substr(__,_,_)
        return (__!~___"$")?!_:match(__,"[^"(___)"]")<_?_\
        :_==index(__,rev2(substr(__,int(length(__)/(++_)))))

    } BEGIN { 

     print "is this palindrome ",\
           is_pdrome(INP)?"yes":"no",\
           "length ::",length(INP)      }'

is this palindrome  yes length :: 13088

mawk -v INP="${a}"   0.00s user 0.00s system 63% cpu 0.011 total
RARE Kpop Manifesto
  • 2,453
  • 3
  • 11
-1
let a = "malayalam"

let check = (a) => {
  let second = a.split("");
  second = second.reverse();
  
  return a === second.join("");
}
console.log(check(a));
Jakub Kurdziel
  • 3,216
  • 2
  • 12
  • 22
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer). – Ethan Sep 01 '22 at 22:13
-2
(function (strOne,strTwo) {
    var a = strOne.toLowerCase().split("").sort().join("")=== 
            strTwo.toLowerCase().split("").sort().join("");

    console.log(a ? ("pallindrome"): ("not a pallindrome"));

})("mommosm","mommom");
  • 1
    Please add some explanation to your answer such that others can learn from it. Why do you sort the characters? Wouldn't this also mark strings as a palindrom that solely use the same characters, but in a completely different order? – Nico Haase Oct 25 '21 at 06:44
-2
function palindrome(str) {
  str = str.toLowerCase();
  if (str[0] == str[str.length - 1]) {
    return true;
  } else {
    return false;
  }
}

// the output

"bcb" is a palindrome‣ " bcb" is not a palindrome‣ "bcb " is not a palindrome‣ "love" is not a palindrome‣ "699996" a palindrome‣ "racecar" a palindrome‣ "Trunk knurt"is case insensitive.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 27 '22 at 08:01