In: Computer Science
Write in javaScript: User input 5 words in one input, and print out the longest word.
Please comment if you have any doubt
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<b>Enter words with space between
them</b><br>
<input type="text" id="words" placeholder="Enter
Words Here"><br>
<input type="button" value="Find Longest Word"
onclick="findLongestWord();">
<script type="text/javascript">
//below function will be called when you click
button
function findLongestWord(){
//the value that is entered in
input field with id words is stored in words
var
words=document.getElementById('words').value;
//Splitting the words with
space
//split('x') will split the string
with x and make it a list
//change the x if you want to use
',','-' or any other separator
var list_of_words=words.split('
');
//assuming that longest word is a
empty string
var longest_word='';
//accessinf each word from
list_of_words
for(i=0;i<list_of_words.length;i++){
//if a word's
length is long then previous one
//then it is
made as new longest word
if(list_of_words[i].length>longest_word.length){
longest_word=list_of_words[i];
}
}
//if no words are entered
if(longest_word=='')
document.write("Enter words");
//Else if words are entered
else
document.write("Longest Word is:"+longest_word);
}
</script>
</body>
</html>
Screenshot:
Output: