Home / Javascript / Find the longest word in a string

Find the longest word in a string

Write a JavaScript function to find the longest word in a string.

Enter string: 'Web Development Tutorial'
Result: 'Development'

Example:

JavaScript: Find the longest word within a string

Source code:


<html>
<head>

Find the longest word within a string


</head>
<body>
  
</body>
</html>

View example

 

Explanation:

Suppose str = '@Web Development #Tutorial';

The match() method is used to retrieve matches when matching a string to a regular expression.
Therefore, str.match (/\w [a-z] {0,}/gi) will return ["Web", "Development", "Tutorial"].

The for loop checks the length of the array element and compares it with the previous element and finally returns the longest string.

The length attribute represents an unsigned 32-bit integer, always numerically greater than the highest index in the array.
Syntax -> arr.length

Algorithm flow chart:

Flowchart: JavaScript function: Find the longest word within a string

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖