javascript code for palindrome code example

Example 1: palindrome in javascript

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

Example 2: palindrome javascript

function palindrome(str) {
 var splitted = str.split("");
 var reversed = splitted.reverse("");
 var joined = reversed.join("");
 return joined.toLowerCase().replace(/[^0-9a-z]/gi, '') == str.toLowerCase().replace(/[^0-9a-z]/gi, '')
}

Example 3: palindrome js

const palindrome = (str) => {
  var text = str.replace(/[.,'!?\- \"]/g, "")
  return text.search(
    new RegExp(
      text
        .split("")
        .reverse()
        .join(""),
      "i"
    )
  ) !== -1;
}
  
//or
function palindrome(str) {
  let text = str.replace(/[.,'!?\- \"]/g, "").toUpperCase();
  for (let i = 0; i > text.length/2; i++) {
    if (text.charAt(i) !== text.charAt(text.length - 1 - i)) {
      return false;
    }
  }
  return true;
}
console.log(palindrome("Able was I, ere I saw elba.")); //logs 'true'