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.
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.
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
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.
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"));
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;
}
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
Let us start from the recursive definition of 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;
}
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.
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 String
s 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.
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())
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.
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;
}
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;
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);
Try this
isPalindrome = (string) => {
if (string === string.split('').reverse().join('')) {
console.log('is palindrome');
}
else {
console.log('is not palindrome');
}
}
isPalindrome(string)
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.
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));
Here's another way of doing it:
function isPalin(str) {
str = str.replace(/\W/g,'').toLowerCase();
return(str==str.split('').reverse().join(''));
}
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>
function isPalindrome(s,i) {
return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}
The code is concise quick fast and understandable.
TL;DR
Explanation :
Here isPalindrome
function accepts a str
parameter which is typeof string.
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.
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>
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;
}
Or you could do it like this.
var palindrome = word => word == word.split('').reverse().join('')
How about this one?
function pall (word) {
var lowerCWord = word.toLowerCase();
var rev = lowerCWord.split('').reverse().join('');
return rev.startsWith(lowerCWord);
}
pall('Madam');
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");
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
}
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
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"));
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');
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/
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;
}
}
}
function palindrome(str){
for (var i = 0; i <= str.length; i++){
if (str[i] !== str[str.length - 1 - i]) {
return "The string is not a palindrome";
}
}
return "The string IS a palindrome"
}
palindrome("abcdcba"); //"The string IS a palindrome"
palindrome("abcdcb"); //"The string is not a palindrome";
If you console.log this line: console.log(str[i] + " and " + str[str.length - 1 - i])
, before the if statement, you'll see what (str[str.length - 1 - i])
is. I think this is the most confusing part but you'll get it easily when you check it out on your console.
All these loops! How about some functional goodness :) May run in to tail call issues on old/current js engines, solved in ES6
function isPalendrome(str){
var valid = false;
if(str.length < 2 ) return true;
function even(i,ii){
str[i]===str[ii] ? ((i+1 !== ii) ? even(i+1,ii-1) : valid = true) : null
}
function odd(i, ii){
str[i]===str[ii] ? ((i !== ii) ? odd(i+1,ii-1) : valid = true) : null
}
if(str.length % 2){
return odd(0,str.length-1),valid;
}else{
return even(0,str.length-1),valid;
}
}
To test your call stack run this code, you will be able to parse strings double the call stack size
function checkStackSize(){
var runs = 70000;
var max_process = 1;
var max = 0;
function recurse_me() {
max_process++;
if(max_process === runs) return;
max = max_process;
try {
recurse_me()
} catch(e) {
max = max_process;
}
}
recurse_me()
console.log(max);
}
Due to the symmetrical nature of the problem you could chunk the string from the outside in and process the chunks that are within call stack limits.
by that I mean if the palindromes length is 1000. You could join 0-250 and 750-1000 and join 250-499 with 500-749. You can then pass each chunk in to the function. The advantage to this is you could run the process in parallel using web workers or threads for very large data sets.
You could also do something like this :
function isPalindrome(str) {
var newStr = '';
for(var i = str.length - 1; i >=0; i--) {
newStr += str[i];
}
if(newStr == str) {
return true;
return newStr;
} else {
return false;
return newStr;
}
}
ES6 way of doing it. Notice that I take advantage of the array method reduceRight to reverse a string (you can use array methods on strings if you give the string as context, as low level - strings are arrays of chars). No it is not as performant as other solutions, but didn't see any answer that came it it using es6 or higher order functions so figured I'd throw this one out there.
const palindrome = str => {
const middle = str.length/2;
const left = str.slice(0, middle)
const right = Array.prototype.reduceRight.call(str.slice(Math.round(middle)), (str, char) => str + char, '')
return left === right;
}
To avoid errors with special characters use this function below
function palindrome(str){
var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();
var checkPalindrome = removeChar.split('').reverse().join('');
if(removeChar === checkPalindrome){
return true;
}else{
return false;
}
}
This tests each end of the string going outside in, returning false as soon as a lack of symmetry is detected. For words with an odd number of letters, the center letter is not tested.
function isPalindrome(word){
var head = 0;
var tail = word.length - 1;
while (head < tail) {
if (word.charAt(head) !== word.charAt(tail)){
return false
} else {
head ++;
tail --;
}
};
return true;
};
function palindrome(s) {
var re = /[\W_]/g;
var lowRegStr = s.toLowerCase().replace(re, '');
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
For better performance you can also use this one
function palindrome(str) {
str = str.split("");
var i = str.length;
var check = "Yes"
if (i > 1) {
for (var j = 0; j < i / 2; j++) {
if (str[j] != str[i - 1 - j]) {
check = "NO";
break;
}
}
console.log(check);
} else {
console.log("YES");
}
}
A simple one line code to check whether the string is palindrome or not:
function palindrome (str) {
return str === str.split("").reverse().join("");
}
<!-- Change the argument to check for other strings -->
<button type="button" onclick="alert(palindrome('naman'));">Click Me<utton>
The above function will return true if the string is palindrome. Else, it will return false.
My short solution, with the length of 66 characters. The result: true or false.
function isPalindrome(s) {
s=s.toLowerCase().match(/\w/g);
return s.join()==s.reverse().join();
}
I think this implementation covers pretty much every case. I hope it's useful to someone:
function isPalindrome(word){
if(typeof word === 'undefined' || word === null){
console.log("argument is undefined");
return;
}
if(typeof word === 'string'){
word = word.replace(/\s/gi,"");
if(word.length < 1){
console.log("wrong argument");
return;
}
if(word.length === 1){
console.log("It's palindrome!");
return;
}
for(var i=0;i<Math.floor(word.length/2);i++){
if(word[i] !== word[word.length - 1 - i]){
console.log("It's not palindrome");
return;
}
}
console.log("It's palindrome");
}else{
console.log("argument must be a string");
}
}
And then you can try with these cases:
isPalindrome("nurses run");
isPalindrome("abcdcba");
isPalindrome("hello world");
isPalindrome(" ");
isPalindrome(" ");
isPalindrome("");
isPalindrome(null);
isPalindrome();
isPalindrome(100);
isPalindrome({"name":"John"});
function Palindrome(str) {
let forwardStr = str.toLowerCase().replace(/[\W_]/g, '');
let reversedStr = forwardStr.split('').reverse().join();
return forwardStr === reversedStr;
}
console.log(Palindrome('madam'));
function reversName(name){
return name
.split('')
.reverse()
.join('') === name ;
};
console.log(reversName('suus'));
console.log(reversName('suusss'));
/* Following function does the below mentioned task.
1. Fetch all the substrings of a given string.
2. Find which of the substrings are palindromes.
3. Find the longest palindrome.
4. Find if the longest palindrome is a lucky palindrome.
*/
function SubstringMnipulations(S) {
let Str = S.toString();
let AllSubStrs = splitSubstrings(Str);
let Pelindromes = arePelindrome(AllSubStrs);
let LongestPelindrome = getLongestString(Pelindromes);
let isPrimeVar = isPrime(LongestPelindrome);
return {
"possibleSubstrings": AllSubStrs,
"pelindromes": Pelindromes,
"longestPelindrome": LongestPelindrome,
"isLuckyPelindrome": isPrimeVar
};
}
function splitSubstrings(Str) {
let StrLength = Str.length;
let maxIndex = StrLength;
let AllSubStrs = [];
for(var index = 0; index < maxIndex; index++ ) {
for(var innerIndex = 1; innerIndex <= maxIndex-index; innerIndex++) {
AllSubStrs.push(Str.substring(index, (index+innerIndex)));
}
}
return AllSubStrs;
}
function arePelindrome(StrArr) {
let pelindrome = [];
for(i=0; i<StrArr.length;i++) {
if(isPelindrome(StrArr[i])) {
if(StrArr[i].length>1) {
pelindrome.push(StrArr[i]);
}
}
}
return pelindrome;
}
function isPelindrome(Str) {
let strLen = Str.length;
let firstHalfIndex = 0;
if(strLen==1) {
return true;
}
let firstHalf = "";
let secondHalf = "";
if(strLen>1 && strLen%2==0) {
firstHalfIndex = strLen/2;
firstHalf = Str.substring(0, firstHalfIndex);
secondHalf = Str.substring((firstHalfIndex), strLen);
} else {
firstHalfIndex = (strLen-1)/2;
firstHalf = Str.substring(0, firstHalfIndex);
secondHalf = Str.substring((1+firstHalfIndex), strLen);
}
secondHalf = reverseString(secondHalf);
return firstHalf === secondHalf;
}
function reverseString(Str) {
return Str.split("").reverse().join("");
}
function getLongestString(Str) {
let lengthCount = [];
for(i=0; i<Str.length;i++) {
lengthCount.push(Str[i].length);
}
return Str[lengthCount.indexOf(Math.max(...lengthCount))];
}
function isPrime(Str) {
let input = Str.length;
let prime = true;
for (let i = 2; i <= Math.sqrt(input); i++) {
if (input % i == 0) {
prime = false;
break;
}
}
return prime && (input > 1);
}
function palindrome(str) {
var re = /[\W_]/g; // or var re = /[^A-Za-z0-9]/g;
var lowRegStr = str.toLowerCase().replace(re, '');
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
console.log(palindrome("A nut for a jar of tuna"));
console.log(palindrome("Helo World"));
What i use:-
function isPalindrome(arg){
for(let i=0;i<arg.length;i++){
if(arg[i]!==arg[(arg.length-1)-i])
return false;
return true;
}}
Here is a 1 line program to check if your string is a palindrome :-
((s) => `Is ${s} a palindrome ? \n Answer is :- ${s.split('').reverse().join('') == s}`)('bob')
Just modify the last parameter of this IIFE to check different inputs. This is perhaps the best solution.
function isPalindrome(str) {
var isPalindrome = true;
if(str.length === 2){
return isPalindrome;
}
for(let i = 0, d = str.length - 1; i<(d-i); i++ )
{
if(str[i] !== str[d - i] ){
return !isPalindrome
}
}
return isPalindrome
}
function isPalindrome(word) {
let strLen = word.length;
word = word.toLocaleLowerCase();
if (strLen === 0 || strLen === 1) {
return true;
}
if (word[0] === word[strLen - 1]) {
return isPalindrome(word.slice(1, strLen - 1) );
}
return false;
}
Alternative solution for using Array.prototype.every()
function palindrome(str) {
return str.split('').every((char, index) => {
return char === str[str.length - index - 1];
});
}
You can try the following code with n/2
complexity
palindrom(word)
{
let len = word.length
let limit = len % 2 ? (len - 1)/2 : (len/2)
for(let i=0; i < limit; i++)
{
if(word[i] != word[len-i-1])
{
alert('non a palindrom')
return
}
}
alert('palindrom')
return;
}
calling the function
palindrom('abba')
var a = 121;
var aNum = a.toString().split("");
var b = aNum.slice(0).reverse();
aNum = aNum.join("");
b = b.join("");
if(aNum==b){
console.log("Its A Palindrome")
}else{
console.log("Its Not A Palindrome")
}
const isPalindrome = str => {
// base case
if(str.length === 1) return true;
if(str.length === 2) return str[0] === str[1];
if(str[0] === str[str.length - 1]) {
return isPalindrome(str.slice(1, -1))
}
return false;
}
you can use recursion
base case
we have a base case (the simple case) if the string is one char we simply returns true.
if it has two chars we check if the first char is identical to the second and we return true if they are.
recursive case
if it is more than two chars we check if the first and last chars are identical or not if they are not we simply return false
but if they are identical so we now want to do the same thing with other chars so we call the same function with the same string but removing the first and last chars because we already know that they are identical and we keep going until we reach the base case.
hope this be useful
some tests
isPalindrome('p') // true
isPalindrome('po') // false
isPalindrome('pp') // true
isPalindrome('pop') //true
const isPalindrome = function (inputValue) {
const input = `${inputValue}`;
for (let char = 0; char < (input.length-1)/2; char++) {
if (input[char] != input[input.length - 1 - char]) {
return false;
}
}
return true;
};
isPalindrome(123); // false
isPalindrome("aba"); // true
isPalindrome(121); // true
isPalindrome("abc"); // false
This code will work for both string and number type input
the easiest way that in my mind is using reduce
function palindrome(str) {
let reversed = str.split('').reduce((acc, char) => char + acc, '');
if (str === reversed) {
return true;
} else {
return false;
}
}
or maybe you like using every
function palindrome(str) {
return str.split('').every((char, i) => {
return char === str[str.length - i - 1];
});
}
function palindrome(no) {
let a = no.toString().split("");
var b = [];
for (var k = a.length - 1; k >= 0; k--) {
b.push(a[k]);
}
var cc = null;
for(var o in a) {
if (a[o] === b[o]) {
cc = true;
} else {
cc = false;
break;
}
}
if (cc) {
console.log('it is palindrome');
} else {
console.log('it is not palindrome');
}
}
palindrome(1)
What about this :
isPalindrome = (txt)=> [...txt].toString() === [...txt].reverse().toString();
isPalindrome('level');
isPalindrome = (txt)=> [...txt].toString() === [...txt].reverse().toString();
console.log(isPalindrome('level'))
we can check that string is palindrome or not with just simple function
public palindrome(str) {
var lowRegStr = str.toLowerCase();
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
this.palindrome("123321");
you will get boolean value, true or false
Below solution will ignore special characters and check whether the input is palindrome or not. If any interviewer asked this kind of question it may helpful
function palindrome(_val) {
var str = _val.toString();
str = str.toLowerCase();
str = str.replace(/[\W_]/g, '');
function palindrome(_val) {
var str = _val.toString();
str = str.toLowerCase();
str = str.replace(/[\W_]/g, '');
function reverse(str1){
var items = str1.split("");
var length = items.length;
var val="";
for(var i=length-1;i>=0;i--){
//console.log(items[i]);
val=val+items[i];
}
return val;
}
function reverse1(str1){
return str1.split("").reverse().join("");
}
var _res = reverse1(str);
if(_res==str)
return true;
else
return false;
}
var _res = palindrome("A man, a plan, a canal. Panama");
console.log(_res);
you can try this without the reverse join and split method. pre-defined method with higher code complexity than develop by self
var result = "";
function reverseNumber(n) {
// reverse the number via loop
for (var i = x.length - 1; i >= 0; i--) {
result += n[i];
}
if(n===result){
return "Palindrome"
}
else{
return "Not Palindrome"
}
}
var x = prompt("Enter a String : ");
console.log(reverseNumber(x))
One of the easiest way is
Reverse the first string and check reversed string with second string, if it matches with First Reversed String it's Palindrome and if it's not then it's not Palindrome.
Let's understand by code:
const firstString = "madam";
const secondString = "MADAM";
function isPalindrome(firstString, secondString){
// Reversing the first string by lowercasing the characters.
const reverseString = firstString.toLowerCase().split("").reverse().join("");
// Checking the reversed string matches with second string
if(reverseString === secondString.toLowerCase()){
return "Palindrome";
} else {
return "Not Palindrome";
}
}
// Calling the function
console.log( isPalindrome(firstString, secondString) );
Hope it helps!
not exactly javascript syntax, but this checker i wrote confirmed a 13,088-digit long string is palindrome on my 2018-laptop in 11 milliseconds :
time mawk -v INP="${a}" '
function _r2utl(_,__,___) {
return ___<__?_r2utl(substr(_,\
int(__/=___)+!!__),__%--___+__,\
___+___)_r2utl(substr(_,___++,\
__=int(__)),__,___)\
:__<___?(_):substr((_)_,___,___)
}
function rev2(_,__,___) {
return ((___=length(_))<(__+=++__))\
?_:_r2utl(_,___,__)
}
function is_pdrome(__,_,___) {
if (__=="") { return __^__ }
___=_^=_;___=substr(__,_,_)
return (__!~___"$")?!_:match(__,"[^"(___)"]")<_?_\
:_==index(__,rev2(substr(__,int(length(__)/(++_)))))
} BEGIN {
print "is this palindrome ",\
is_pdrome(INP)?"yes":"no",\
"length ::",length(INP) }'
is this palindrome yes length :: 13088
mawk -v INP="${a}" 0.00s user 0.00s system 63% cpu 0.011 total
let a = "malayalam"
let check = (a) => {
let second = a.split("");
second = second.reverse();
return a === second.join("");
}
console.log(check(a));
(function (strOne,strTwo) {
var a = strOne.toLowerCase().split("").sort().join("")===
strTwo.toLowerCase().split("").sort().join("");
console.log(a ? ("pallindrome"): ("not a pallindrome"));
})("mommosm","mommom");
function palindrome(str) {
str = str.toLowerCase();
if (str[0] == str[str.length - 1]) {
return true;
} else {
return false;
}
}
// the output
"bcb" is a palindrome‣ " bcb" is not a palindrome‣ "bcb " is not a palindrome‣ "love" is not a palindrome‣ "699996" a palindrome‣ "racecar" a palindrome‣ "Trunk knurt"is case insensitive.