w3resource

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:

JavaScript: Find the longest word within a string

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:

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

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.



Follow us on Facebook and Twitter for latest update.

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