How to get the biggest word from a string in Javascript?

Asked

Viewed 945 times

-1

Hello, I wonder how I get the biggest word from this string below:

var string = "Bom dia a todos!"
  • A detail: the solution with split considers that punctuation is part of the word. So if the phrase is "Vai lá!!!", she considers that lá!!! is the largest "word". Already the solution with regex considers numbers as well, so if the phrase is vai 1234, she considers that 1234 is the greatest "word". Not to mention that \w also considers the character _, then ___ is also considered a word. And none of the cases treats compound words ("hummingbird" is a single word). Anyway, the answers may or may not be right, depending on the definition of "word"...

3 answers

2


There are several ways to do this, see below some examples:

//String que será avaliada
let string = "Bom dia a todos!";

//Declaro a maior string vazia
let big = "";

//Transformo a string em uma lista com o split, separando por espaços em branco
string.split(" ").forEach(word => {
  if (word.trim().length > big.length) {
    big = word.trim();
  }
});

console.log(big);

//Também transformo a string em uma lista com o split, mas utilizo do reduce para retornar a maior palavra
let bigger = string.split(" ").reduce( (acumulador, valorCorrente) => {
  if (acumulador.length < valorCorrente.trim().length) {
    return valorCorrente.trim();
  }

  return acumulador;
}, "");

console.log(bigger);

//Novamente o split, mas dessa fez é efetuado um for simples
let palavras = string.split(" ");
let bigFor = "";

for (word of palavras) {
  if (word.trim().length > bigFor.length) {
    bigFor = word.trim();
  }
}

console.log(bigFor);

Explanation: Using the split in the string, we can generate a list, we use space as the basis for this. With the list in hand, we have several ways to verify which is the largest string, so we use the property length of the string. There are three examples, one making a forEach in the list, other using the reduce and finally a very simple loop.


References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  • A detail: you consider that punctuation is part of the word. So if the phrase is "Vai lá!!!", the greatest "word" will be lá!!!. Of course the question lacked to better define what it wants (if they are only words from the point of view of grammar, or "anything other than space"), but anyway, it is a point of attention :-)

1

The logic used below separates the words using the split and saving in an array and a foreach traversing the array and checking the amount of letters at each position of the arrayStr

function maiorPalavra(string) {
    var arrayStr = string.split(" ");
    var maior = 0;
    var palavra = null;
    arrayStr.forEach(function(str) {
        if (maior < str.length) {
            maior = str.length;
            palavra = str;
        }
    });
    return palavra;
}
console.log(maiorPalavra("bom dia a todos"));

1

One more way using regex, sorting by word size and picking the first element.

const string = "Bom dia a todos!";

const result = string
  .match(/\w+/g)
  .sort((a, b) => b.length - a.length)[0];
  
console.log(result);

  • This is amazing +1.

  • One detail is that \w also considers numbers and the character _, then if the phrase is vai 1234, the number 1234 will be considered the greatest "word", and things like ___, a2 and _123_ will also be considered words. Of course the question lacked better define what is a word, but anyway, it is a point of attention :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.