Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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.



JavaScript: Tips of the Day

How to insert an item into an array at a specific index (JavaScript)?

What you want is the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

Ref: https://bit.ly/2BXbp04