Certainly! You can create a JavaScript program that takes a string and returns the length of the longest word in that string. Here's an example:
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Certainly! You can create a JavaScript program that takes a string and returns the length of the longest word in that string. Here's an example:
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.