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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…