Introduction
Finding the longest word in a string is a common problem in programming. In JavaScript, this can be achieved by splitting the string into individual words and then finding the word with the maximum length. This guide will walk you through writing a JavaScript program to find the longest word in a given string.
Problem Statement
Create a JavaScript program that:
- Accepts a string.
- Identifies and returns the longest word in the string.
Example:
Input:
"The quick brown fox jumps over the lazy dog"
Output:
"jumps" with length 5
Input:
"JavaScript is an amazing programming language"
Output:
"programming" with length 11
Solution Steps
- Read the Input String: Provide a string either by user input or as part of a method.
- Split the String into Words: Use the
split()
method to break the string into an array of words. - Find the Longest Word: Iterate through the array to find the word with the maximum length.
- Display the Result: Print the longest word and its length.
JavaScript Program
// JavaScript Program to Find the Longest Word in a String
// Author: https://www.javaguides.net/
function findLongestWord(str) {
// Step 1: Split the string into words
const words = str.split(' ');
// Step 2: Find the longest word
let longestWord = words.reduce((longest, currentWord) => {
return currentWord.length > longest.length ? currentWord : longest;
}, "");
// Step 3: Display the result
console.log(`The longest word is: "${longestWord}" with length ${longestWord.length}`);
}
// Example input
let inputString = "The quick brown fox jumps over the lazy dog";
findLongestWord(inputString);
Output Example
The longest word is: "jumps" with length 5
Explanation
Step 1: Split the String into Words
- The
split()
method is used to break the string into an array of words. Each word is separated by spaces in the string.
Step 2: Find the Longest Word
- The
reduce()
function iterates through the array of words and compares the length of each word with the longest word found so far. The word with the maximum length is stored in thelongestWord
variable.
Step 3: Display the Result
- The longest word and its length are printed to the console.
Output Example with Different Input
If you modify the input string to:
let inputString = "JavaScript is an amazing programming language";
The output will be:
The longest word is: "programming" with length 11
Conclusion
This JavaScript program demonstrates how to find the longest word in a string using the split()
and reduce()
methods. By leveraging JavaScript's array manipulation functions, the code is concise and easy to understand. This exercise is useful for learning how to manipulate strings and arrays in JavaScript, as well as solving text-related problems in an efficient manner.
Comments
Post a Comment
Leave Comment