Search code examples
javascriptpalindrome

How can I create a pallindrome code in JavaScript?


So I am trying to create a code for palindrome this is how I tried. Is there another or better way of doing it?

But now it only shows that if the first value is equal or not and shows true or false?

var inpo= prompt("Please enter to check if palindrome")
var inp = parseFloat(inpo)
var a = inpo.split('')
var inpo2 = a.reverse()
var len= inpo.length

for (var i =0;i< len ;i++) { 
  if (inpo[i] == inpo2[i] )
    alert("True")
  else
    alert("False")
}

Solution

  • You can check the single character from the string consuming 1 character from right and another from left until you will find either the string is finished or there are 2 inequal character. I implemented with a classical for loop. Note that bracket notation for strings [] is only recently supported, you can use charAt if memory serves me right

    let inp = "otdto";
    
    console.log(isPalindrome(inp));
    
    function isPalindrome(inp) {
      const len = inp.length;
      for (let i = 0; i < Math.floor(len / 2); i++)
        if (inp[i] != inp[len - i - 1])
          return false;
    
      return true;
    }