Untitled

 avatar
unknown
plain_text
2 years ago
2.4 kB
42
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Palindrome</title>
</head>
<body  >
    <label for="">Enter a phrase: </label>
    <input type="text" id="phrase">
    <br>
    <label for="">Minimum word length</label>
    <input type="number"  id="min"><br>
    <label for="">Maximum word length</label>
    <input type="number"  id="max">
    <br>
    <button type="submit" onclick="findPalindromes()">Find Palindromes</button>
    <ul id="ul"></ul>
</body>
<script>
   function findPalindromes()
    {
        //Get the string inputted by user
        var inputString=document.getElementById("phrase").value
        var minLength=document.getElementById("min").value
        var maxLength=document.getElementById("max").value

        // Split the user input string to a wordList
        var wordList=inputString.split(" ")
        //  Get the html element by id ul to variable list
         var list = document.getElementById("ul");
        //  Clear the innerhtml in list to remove any previous items
        list.innerHTML=""
        // For each word in wordList repeat the loop
         wordList.forEach(word => {
          // find the length of word
             const len = word.length;
            //  If minLength and maxLength is entered then check plaindrome only if the word length is in limit
          if( (!maxLength && len>=minLength) || (!minLength && len<=maxLength) ||  (len>=minLength && len<=maxLength) )
          {  
            //  Check whether the word is palindrome by calling isPalindrome function
            if(isPalindrome(word)){
                // Add the word to list
            var listItem = document.createElement("li");
            list.appendChild(listItem);
             listItem.innerHTML=word
            }
        }
        });
    }
    function isPalindrome(word) {

// find the length of word
const len = word.length;
// Convert the word to uppercase to avoid case sensitivity
word=word.toUpperCase()
// loop through half of the word
for (let i = 0; i < len / 2; i++) {

    // check if first and last characters are same
    if (word[i] !== word[len - 1 - i]) {
        return false;
    }
}
return true;
}

</script>
</html>