Skip to content
the poor coder

LongestWord javascript

Poor Man
Published
Reading time
2 min read
On this page

LongestWord javascript#

Have you ever faced a situation where you need to find the longest word in a string? Well, JavaScript has got you covered. Here are a few ways you can achieve this:

Method 1:#

You can use the split() method to split the string into an array of words and then use a loop to iterate through the array and find the longest word. Here's the code:

Text

function longestWord(str) {
  var words = str.split(' ');
  var maxLength = 0;
  var longestWord = '';

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
      longestWord = words[i];
    }
  }

  return longestWord;
}

console.log(longestWord('The quick brown fox jumped over the lazy dog')); // Output: 'jumped'

Method 2:#

You can also achieve this using the reduce() method. Here's the code:

Text

function longestWord(str) {
  var words = str.split(' ');

  var longestWord = words.reduce(function(longest, currentWord) {
    return currentWord.length > longest.length ? currentWord : longest;
  }, '');

  return longestWord;
}

console.log(longestWord('The quick brown fox jumped over the lazy dog')); // Output: 'jumped'

Method 3:#

If you want to be fancy, you can use map(), sort(), and pop() to achieve the same result. Here's the code:

Text

function longestWord(str) {
  var words = str.split(' ');

  var sortedWords = words.map(function(word) {
    return word.replace(/[^\w]/g, '');
  }).sort(function(a, b) {
    return b.length - a.length;
  });

  return sortedWords[0];
}

console.log(longestWord('The quick brown fox jumped over the lazy dog')); // Output: 'jumped'

These are just a few ways you can find the longest word in a string using JavaScript. Choose the one that works best for your use case.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC