Reputation:
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>
Upvotes: 1
Views: 8850
Reputation: 11
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());
Upvotes: 0
Reputation: 5813
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));
Upvotes: 6
Reputation: 119847
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;
}, '');
Upvotes: 0
Reputation: 1758
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);
Upvotes: 0