JavaScript: Find the longest word within a string
JavaScript Function: Exercise-6 with Solution
Write a JavaScript function that accepts a string as a parameter and find the longest word within the string.
Sample Data and output:
Example string: 'Web Development Tutorial'
Expected Output: 'Development'
Pictorial Presentation:

Sample Solution: -
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Find the longest word within a string</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function find_longest_word(str)
{
var array1 = str.match(/\w[a-z]{0,}/gi);
var result = array1[0];
for(var x = 1 ; x < array1.length ; x++)
{
if(result.length < array1[x].length)
{
result = array1[x];
}
}
return result;
}
console.log(find_longest_word('Web Development Tutorial'));
Sample Output:
Development
Explanation:
Assume str = '@Web Development #Tutorial';
The match() method is used to retrieve the matches when matching a string against a regular expression.
Therefore str.match(/\w[a-z]{0,}/gi) will return ["Web", "Development", "Tutorial"].
For loop checks the length of the array element and compare with previous one and finally return the longest string.
The length property represents an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
Syntax -> arr.length
Flowchart:

Live Demo:
See the Pen JavaScript -Converts the first letter of each word of a string in upper case-function-ex- 5 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript function that accepts a string as a parameter and converts the first letter of each word of the string in upper case.
Next: Write a JavaScript function that accepts a string as a parameter and counts the number of vowels within the string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
Shorten an array using its length property
A great way of shortening an array is by redefining its length property.
let array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9] array.length = 4 // Result: [0, 1, 2, 3]
Important to know though is that this is a destructive way of changing the array. This means you lose all the other values that used to be in the array.
Ref: https://bit.ly/2LBj213
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises