简体   繁体   中英

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');

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM