Austin Hansen
Austin Hansen

Reputation: 374

Split String into Array of Words to find Longest

I am working on a task to search any given string for the longest word. I am thinking the ideal way to do this is to split the string into an array consisting of each word then looping through that array and comparing each length to return the longest. I am stuck on just separating the string into an array of words. The questions I have seen answered similar in topic seem to use much to complicated methods for such a simple task. I am looking for help on a beginner level as this is my first time incorporating regular expressions into my code.

function findLongestWord(str) {
     str = str.toLowerCase().split("/\w+");
     return str;
}

findLongestWord('The quick brown fox jumped over the lazy dog');

Upvotes: 0

Views: 1104

Answers (2)

Oka
Oka

Reputation: 26345

Your regex is structured poorly. Even if it was fixed, .split(/\w+/), splitting on the words would create an array with results opposite of what you are looking for.

You should be using .match to collect the words.

function findLongestWord(str) {
  var match = '';

  str.match(/\w+/gi).forEach(function (w) {
    if (w.length > match.length) {
      match = w;
    }
  });
  
  return match;
}

var a = findLongestWord('The quick brown fox jumped over the lazy dog');

console.log(a);

Still slightly naive, since words can have hyphens in the middle, and apostrophes on the front, in the middle, and on the end.

Upvotes: 2

user4938328
user4938328

Reputation:

function findLongest(str){
    var array = str.split(" ");
    var longest = "";
    for (var i=0; i<array.length; i++){
        if (array[i].length > longest.length){
            longest = array[i];
        }
    }
    console.log(longest);
}
findLongest("The quick brown fox jumped over the lazy dog");

Upvotes: 1

Related Questions