Find the Longest Word in a String

JavaScript

Function to find the longest word in a given sentence:

You can create a JavaScript function to find the longest word in a given sentence by splitting the sentence into words and then iterating through each word to find the one with the maximum length. Here's how you can do it:

js Copy Code
function longestWord(sentence) {
    // Split the sentence into words
    let words = sentence.split(/\s+/);
    
    // Initialize variables to store the longest word and its length
    let longest = "";
    let maxLength = 0;
    
    // Iterate through each word to find the longest one
    for (let i = 0; i < words.length; i++) {
        // Remove any punctuation from the word
        let word = words[i].replace(/[^\w\s]/g, '');
        
        // Check if the current word is longer than the current longest word
        if (word.length > maxLength) {
            longest = word;
            maxLength = word.length;
        }
    }
    
    return longest;
}

// Example usage
let sentence = "The quick brown fox jumps over the lazy dog.";
console.log("Longest word:", longestWord(sentence));
Output:
Longest word: quick

Explanation:

This function 'longestWord()' takes a sentence as input and returns the longest word in that sentence. It splits the sentence into words using a regular expression, removes any punctuation from each word, and then iterates through the words to find the longest one. Finally, it returns the longest word found.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.