Tutorialspoint
Problem
Solution
Submissions

Find Longest Word in a String

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 5

Write a JavaScript program to find the longest word in a given string. The function should return the longest word found in the string. If there are multiple words with the same maximum length, return the first one encountered. Words are separated by spaces, and you should ignore punctuation marks.

Example 1
  • Input: str = "The quick brown fox jumps over the lazy dog"
  • Output: "quick"
  • Explanation:
    • Split the string into individual words: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"].
    • Check the length of each word: The(3), quick(5), brown(5), fox(3), jumps(5), over(4), the(3), lazy(4), dog(3).
    • The longest words are "quick", "brown", and "jumps" with 5 characters each.
    • Return the first occurrence which is "quick".
Example 2
  • Input: str = "JavaScript is awesome and powerful"
  • Output: "JavaScript"
  • Explanation:
    • Split the string into words: ["JavaScript", "is", "awesome", "and", "powerful"].
    • Check lengths: JavaScript(10), is(2), awesome(7), and(3), powerful(8).
    • "JavaScript" has the maximum length of 10 characters.
    • Return "JavaScript" as it's the longest word.
Constraints
  • 1 ≤ str.length ≤ 1000
  • The string contains only alphabetic characters and spaces
  • There will be at least one word in the string
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(n) for storing the split words
StringsEYPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Split the string into an array of words using the split() method
  • Initialize variables to track the longest word and its length
  • Iterate through each word in the array
  • Compare the current word's length with the maximum length found so far
  • Update the longest word if a longer word is found
  • Return the longest word after checking all words

Steps to solve by this approach:

 Step 1: Split the input string into an array of individual words using the split(' ') method
 Step 2: Initialize variables to keep track of the longest word found and its length
 Step 3: Iterate through each word in the words array using a for loop
 Step 4: For each word, compare its length with the current maximum length
 Step 5: If the current word is longer, update both the longest word and maximum length variables
 Step 6: Continue the iteration until all words have been processed
 Step 7: Return the longest word found after completing the iteration

Submitted Code :