Find the longest word in a given string using JavaScript?

Answered
suparman21 asked this question 21 days ago
suparman21 21 days ago

As the title states, how do I get the largest string in a given word?

For example, if I'm given a string like this:

let string = "An example string with a loooooooooong word!"

The function or method should return the "loooooooooong" string, which is the longest word in the original string.

How can I do this using JavaScript?

4 suggested answers
·
1 reply
nick 13 days ago

Give this a try:

var string = "An example string with a loooooooooong word!"

// convert string to an array of strings containing each word
var array = string.split(" ")

// sort array in descending order from longest to shortest
// return the first word from the newly sorted array
  // which will be the longest one
var longest = array.sort(function(a, b) {
  return b.length - a.length
})[0]

// longest = "loooooooooong"
0 replies
itsbambi 12 days ago
var longestWord = string.split(" ").reduce(
  function (a, b) {
    return a.length > b.length ? a : b
  }
)
1 reply
suparman21 12 days ago

This is the easiest way!

Thanks for the help on this :)

looper003 12 days ago

This function will take your string and return the longest word that it contains:

function getLongestWord(string) {
  var array = string.split(" ")

  var length = 0
  var longest = ""

  for (var i=0; i < array.length; i++) {
    if (array[i].length > longest.length) {
      longest = array[i]
    }
  }

  return longest
}
0 replies
yaboy01 12 days ago

A method you can apply directly to a string:

String.prototype.getLongestWord = function() {
  let arrayOfWords = this.split(" ")

  let longestWord = ""

  arrayOfWords.forEach(function(word) {
    if (word.length > longestWord.length) longestWord = word
  })

  return longestWord
}

string.getLongestWord()
0 replies
Answered