Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

html - Find out the longest word from a sentence - Javascript

Is there any way to find out the longest word in Javascript? It should ignore punctuation marks too!

I understood the logic, but the code... sigh

Here's what we do -

  1. Count the number of alphanumeric characters that are together, not separated by a space or any sign.

  2. Get their lengths.

  3. Find the biggest length in all.
  4. Return the word with the biggest length.

Hope I'm making myself clear...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Split the string, loop over the parts and keep track of the longest one.

Something like this:

var parts = sentence.split();
var longestIndex = -1;
var longestWord = 0;

for(var i=0; i < parts.length; i++){
    if(parts[i].length > longestWord){
        longestWord = parts[i].length;
        longestIndex = i;
    }
}

alert("longest word is " + parts[longestIndex] + ": " + longestWord + " characters");

If you need to split on non alphabetic characters as well as spaces you need to use regexes. You can change this line:

var parts = sentence.split();

To this (thanks Kooilnc for the regex):

var parts = sentence.match(/w[a-z]{0,}/gi);

Working jsfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...