1

folks, I'm trying to find out what word is the longest in an entered sentence but the code is not outputting anything. Could smb please help me with that?

<!DOCTYPE html>
<html>
<head lang = "en">
    <meta charset = "UTF-8">
    <title>LongestWord</title>
</head>
<body>
<script language = "Javascript" type = "text/javascript">
    var sentence = prompt("Enter sentence: ");
    var splitted = sentence.split("\\s+");
    var longestWord = splitted[0];

    for(var i = 0; i < splitted.length; i++){
        for(var j = 0; j < splitted[i].length - 1; j++){
            if(longestWord.length < splitted[i].length){
                longestWord = splitted[i];
            }

        }
    }
    document.write("The longest word in the sentence is " + longestWord);  
</script>
</body>
</html>
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • It should be `var i = 1` instead since you already taken splitted[0] in variable. – Rahul Jun 28 '15 at 22:39
  • look here http://stackoverflow.com/questions/12216758/find-out-the-longest-word-from-a-sentence-javascript – banksy Jun 28 '15 at 22:48

4 Answers4

6

Change your regexp code to:

var splitted = sentence.split(/\s+/);

EDIT: below is a slightly different take on the function:

function longestWord(str) {
    return str.split(/\s+/).sort(function(w1, w2) {return w2.length - w1.length;})[0];    
}

var phrase = "dmitriy nesterkin drd";
console.log(longestWord(phrase));
DRD
  • 5,557
  • 14
  • 14
0
var length = 0;
var longestWord = "";
sentence.split(" ").forEach(function(word){
  if(word.length > length) {
    length = word.length;
    longestWord = word;
  }
});
document.write("The longest word in the sentence is " + longestWord);
ChadF
  • 1,750
  • 10
  • 22
0

Here's a simplified version, using split and reduce. First spotted word prevails.

var longestWord = sentence.split(' ').reduce(function(longestWord, word){
  return word.length > longestWord.length ? word : longestWord;
}, '');
Joseph
  • 117,725
  • 30
  • 181
  • 234
0

You could make a compare function for the sort() function easily. This way you can check if there is more than one word that matches the length of the longest word, by popping the resulting sorted array.

function compare_words(a, b) { return a.length - b.length; }

var words = ["Hello", "here", "are", "some", "words", "of", "variable", "length"];

console.log("Longest word is: " + words.sort(compare_words).pop());
Dunn
  • 11
  • 1