0

Please solve my issue, I am going to check a list of strings as palindrome, if any of the string from the array is palindrome then it should display a result true, the result should be in string value not in Boolean value. I had tried so many times but it is not displaying the result; See my code below:-

function checkPry()
{
    var status = new Array();
    var wordList1 = document.getElementById("tk").value;
    var wordArray = new Array();
    wordArray = wordList1.split(" "); 
    var alength = wordArray.length; 
    for(var i=0; i <= alength; i++)
    {
        var str = wordArray[i];
        var chrlength = str.length;
        var lw = chrlength - 1;
        var chk = "";
        for(j=0; j<=chrlength; j++)
        {
            if(str.charAt(j) != str.charAt((lw - j)))
            {
                chk = "false";
                break;
            }
            else
            {
                chk = "true";
            }
        }
        if (chk == "true")
        {
            status[i] = "true";
        }
        else if (chk == "false")
        {
            status[i] = "false"
        }
    }
    var displayStr = status.toString();
    document.getElementById("show").innerHTML = displayStr;
}

like If I am giving the input value as [dalad radar jaijai rexem] then it should be give result as [true,true,false,false], Please help me in that; you can also check the fiddle below:--

http://jsfiddle.net/yePQ4/1/

Thanks!

Josh Durham
  • 1,632
  • 1
  • 17
  • 28
N.P. SINGH
  • 303
  • 1
  • 4
  • 15

2 Answers2

5

You just need to check if something reversed is the same

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

function checkIsPalindrome(arr){
   var result=[];
   for(var i=0;i<arr.length;i++){
       result.push(arr[i]==reverse(arr[i]));
   }
   return result;
}
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
2

Just for fun, here's an alternate version of @scrblnrd3's answer that uses a regex to reverse the string instead of split/join.

function reverse(text) {
    return text.replace(/./g, function(c, i, s) { return s[s.length - 1 - i]; });
}

function checkIsPalindrome(arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        result.push(arr[i] == reverse(arr[i]));
    }
    return result;
}
Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141