Find the Longest Word in a String in JavaScript

In this example, you will learn how to write a JavaScript program to find the longest word in a given string in JavaScript.

Basically, we are going to learn different ways to find the longest word in a given string in JavaScript.

JavaScript Program to Find the Factorial of a Number

Three ways to find the longest word in a given string in JavaScript.

  1. With a for loop
  2. With sort method
  3. With reduce method

main.js

Let's create a main.js file and add the following code to it:

// 1. With a for loop

function findLongestWordV1(str) {
  var strSplit = str.split(' ');
  var longestWord = '';
  var longestWordLength = 0;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longestWordLength){
      longestWordLength = strSplit[i].length;
	    longestWord = strSplit[i];
    }
  }
  return longestWord;
}


// 2. With sort method

function findLongestWordV2(str) {
  var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
  return longestWord[0];
}

// 3. With reduce method
function findLongestWordV3(str) {
  var longestWord = str.split(' ').reduce(function(longest, currentWord) {
    return currentWord.length > longest.length ? currentWord : longest;
  }, "");
  return longestWord;
}

// Testing
console.log(findLongestWordV1("JavaScript is most popular programming language"));
console.log(findLongestWordV2("JavaScript is most popular programming language"));
console.log(findLongestWordV3("JavaScript is most popular programming language"));

Note that the comments in the above code are self-descriptive.

index.html

To test JavaScript code, let's create an HTML file named index.html and add the following code to it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="main.js"></script>
</body>
</html>

Note that we have included the main.js file as an external JavaScript file:

<script src="main.js"></script>

Run index.html in Browser

Run above index.html file in browser and open dev tools console to see the output of the JavaScript code:

programming
programming
programming

Related JavaScript Examples

Comments