Find Substrings which are palindrome

Find Substrings which are palindrome

We come across various situation where we need to find the substring from a given string which are palindrome.

Here is how you can achieve it using JavaScript.

function allPalindrome(str){
  var arr = str.split("");
  var allPalindrome = [];
  
  for(var i = 0; i < arr.length; i++){
    var temp = "";
    temp = arr[i];
    for(var j = i + 1; j < arr.length; j++){
      temp += arr[j];
      if(temp.length > 2 && temp === temp.split("").reverse().join("")){
        allPalindrome.push(temp);
      }
    }
  }
return allPalindrome;
}

Output

var palindromes = longestPalindrome("abc123321");

console.log(palindromes);

["123321", "2332"]

 

Leave a Reply

Your email address will not be published. Required fields are marked *