find longest word in a string

前端 未结 3 1042
别跟我提以往
别跟我提以往 2021-01-15 05:01

Currently trying to figure out how to find the longest word in as string and my research has gotten me somewhere. I found a code on SO that shows the amount of alphabets in

3条回答
  •  抹茶落季
    2021-01-15 05:06

    I recommend this approach:

    function LongestWord(text) {
        return text
                  .split(/\s+/)
                  .reduce(function (record, word) {
                      if (word.length > record.length)
                          record = word;
                      return record;
                  }, '');
    }
    console.log(LongestWord('It is obvious which is the longest word.'));
    

    If you want to return the length of the longest word, just add .length to the end of the return.

提交回复
热议问题