how do you make a text box and a longest word button in javascript to find the longest word in a phrase on html -


file text box , longest word button. in case of ties in "many dogs nice", can identify of longest words longest.

a function gets string , returns longest word in it:

function getlongestword(txt) {     var longestword = "";     var words = txt.split(" ");     for(var = 0; < words.length; i++)         if(words[i].length > longestword.length)             longestword = words[i];     return longestword; } 

explanation:

  • longestword - @ beginning empty - hold our current longest word.

  • since space separates different words, function first splits input string based on space character , stores them array.

  • we iterate through array of words , check length of each 1 of them. if new word has bigger length, it'll replace longestword, otherwise no change , go next word till words checked.

html:

<textarea id="mytext"></textarea> <button id="longestbtn">find longest word</button> <input id="longestwrd" type="text" disabled /> 

javascript:

var btn = document.getelementbyid('longestbtn'); btn.addeventlistener('click', function () {     var txt = document.getelementbyid('mytext').value;     var lw = getlongestword(txt);     var wrd = document.getelementbyid('longestwrd');     wrd.value = lw + " (" + lw.length + ")"; }); 

jsfiddle demo

test input:

file text box , longest word button. in case of ties in "many dogs nice", can identify of longest words longest.

output:

identify (8)


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -