how to check for palindrome in javascript 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: how to check palindrome in javascript for lowercase and uppercase
function palindrome(str) {
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re, '');
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
palindrome("A man, a plan, a canal. Panama");
Example 3: palindrome js
const palindrome = (str) => {
var text = str.replace(/[.,'!?\- \"]/g, "")
return text.search(
new RegExp(
text
.split("")
.reverse()
.join(""),
"i"
)
) !== -1;
}
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."));