42

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.

2
  • 28
    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. Commented Mar 1, 2014 at 7:31
  • 1
    This was already asked and answered a few times stackoverflow.com/a/20662606/437019 Commented Mar 5, 2014 at 12:52

68 Answers 68

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

Sign up to request clarification or add additional context in comments.

9 Comments

Also note that in your first example you only need to traverse half the string length.
@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.
@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
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++)
So far as I can tell, charCodeAt(n) is always faster. See jsfiddle.net/7q1jo31e/2, per my answer earlier stackoverflow.com/a/22343688/1888292
|
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!

8 Comments

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
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?
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.
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?
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.
|
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")); 

2 Comments

@rightfold I would say it's more verbose. You can instantly see that it'll be returning a boolean.
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.
9
+50

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;
} 

5 Comments

I am pretty sure that modern JS engines can optimize out the .length access
+1 for the traversing half the original string length (other answers seem to have missed this for some reason).
@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 Then at least it shouldn't be stated that it's ultimately faster, but I see you've already done the edit.
But you recalculate wLength/2 + 1 and wLength-1 at every iteration of the loop.
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;
}

Comments

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

1 Comment

Now it does half the comparisons..you can't do less
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.

1 Comment

Noteworty use of |0 to cast to integers.
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.

2 Comments

Again, comparsion of the whole string instead of the half.
Please share more details. Why is this the "best way"?
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())

Comments

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.

2 Comments

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, 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 (breaking 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.
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;

}

Comments

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);

Comments

2

Try this

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

isPalindrome(string)

Comments

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;

Comments

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.

7 Comments

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 It will take floor value.
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.
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. :-)
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 :)
|
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));

Comments

1

Here's another way of doing it:

function isPalin(str) {
  str = str.replace(/\W/g,'').toLowerCase();
  return(str==str.split('').reverse().join(''));
}

Comments

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>  

Comments

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.

Comments

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>

Comments

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;
    }

Comments

1

Or you could do it like this.

var palindrome = word => word == word.split('').reverse().join('')

1 Comment

like this answer, could be done like this as well: const palindrome = word => word == [...word].reverse().join('')
1

How about this one?

function pall (word) {

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

    return rev.startsWith(lowerCWord);
    }

pall('Madam');

Comments

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");

Comments

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
}

Comments

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

Comments

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"));

Comments

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');

Comments

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/

1 Comment

Unorthodox placement of the index increment outside the for-arguments.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.