How to find longest word using JavaScript

Welcome to our journey into JavaScript, where we’ll solve the puzzle of finding the longest word in a sentence! Join us as we explore simple code and explanations to create a useful tool. Let’s dive in and discover the magic of JavaScript together!

HTML

To begin our journey, let’s create our playground using HTML. Here, you’ll see a spot where you can type in your sentence and see the longest word appear!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Longest Word Explorer</title>
</head>
<body>
    <label for="sentence">Enter a Sentence:</label>
    <input type="text" id="sentenceInput" oninput="findLongestWord()">
    <p>Longest Word Found: <span id="longestWordDisplay"></span></p>

    <script>
        // Our JavaScript Adventure Begins Here!
        function findLongestWord() {

            // Step 1: Get the input field and display area
            const inputField = document.getElementById('sentenceInput');
            const longestWordDisplay = document.getElementById('longestWordDisplay');

            // Step 2: Retrieve the sentence entered by the user
            const sentence = inputField.value;

            // Step 3: Split the sentence into individual words
            const words = sentence.split(' ');

            // Step 4: Initialize a variable to store the longest word
            let longestWord = '';

            // Step 5: Iterate through each word to find the longest one
            words.forEach(word => {
                if (word.length > longestWord.length) {
                    longestWord = word;
                }
            });

            // Step 6: Display the longest word in the designated area
            longestWordDisplay.textContent = longestWord;
        }
    </script>
</body>
</html>

JavaScript Explanation(See Steps in code comments)

  • Step 1-2: We start by getting references to the input field and the area where we’ll display the longest word.
  •   Step 3-5: Next, We split the sentence into individual words, explore each word’s length, and capture the longest one.
  •    Step 6: Finally, we reveal the longest word by displaying it in the designated area for all to see!

In our JavaScript tutorial, we’ve not only figured out how to find the longest word but also learned more about how JavaScript and HTML work together to make fun and interactive experiences. Keep exploring and have fun coding!

Leave a Comment