---
title: "Write a javascript program that takes a string and returns the longest word length."  
description: "Write a javascript program that takes a string and returns the longest word length."  
author: "Revati S Misra"  
published: 2023-04-14  
updated: 2023-11-26  
canonical: https://www.mindstick.com/forum/157802/write-a-javascript-program-that-takes-a-string-and-returns-the-longest-word-length  
category: "javascript"  
tags: ["javascript"]  
reading_time: 2 minutes  

---

# Write a javascript program that takes a string and returns the longest word length.

Write a [javascript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript) [program that takes](https://www.mindstick.com/forum/157801/write-a-javascript-program-that-takes-an-array-of-numbers-and-returns-the-highest-number) a [string and returns](https://www.mindstick.com/forum/157804/write-a-javascript-program-that-takes-a-string-and-returns-a-new-string-with-capitalized-words) the longest [word](https://www.mindstick.com/forum/305/read-word-file) length.

## Replies

### Reply by Aryan Kumar

Certainly! You can create a JavaScript [program](https://www.mindstick.com/blog/12337/scaling-up-your-mentorship-program) that takes a [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) and returns the length of the longest word in that string. Here's an example:

```plaintext
function longestWordLength(inputString) {
  // Split the input string into an array of words
  const words = inputString.split(/\s+/);

  // Find the length of the longest word using reduce
  const maxLength = words.reduce((max, word) => {
    return Math.max(max, word.length);
  }, 0);

  return maxLength;
}

// Example usage:
const inputString = 'This is a sample string with varying word lengths.';
const result = longestWordLength(inputString);

console.log(result); // Outputs: 7 (for the word "varying")
```

In this example, the **longestWordLength** function takes an input string, splits it into an array of words using a regular expression (**/\s+/** to handle different types of whitespace), and then uses the **reduce** method to find the length of the longest word.

The **reduce** function takes a callback function with an accumulator (**max**) and the current element of the array (**word**). It compares the length of each word with the current maximum length and updates the maximum accordingly.

The example usage demonstrates how to use the function with a sample input string, and the result (length of the longest word) is printed to the console.


---

Original Source: https://www.mindstick.com/forum/157802/write-a-javascript-program-that-takes-a-string-and-returns-the-longest-word-length

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
