简体   繁体   中英

How to find the length of the largest word in a string with javascript?

 function findLongestWordLength(str) { var res = str.split(" "); var ar = []; for (let i = 0; i < res.length; i++) { let leength = res[i].length; ar.push(leength); //ar is the array of the lengths of the word in the string. } var largest = 0; for (let i = 0; i <= largest; i++) { if (ar[i] > largest) { var largest = ar[i]; } //this loop is detecting largest number from the array ar. } return largest; } console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"));

I want the largest word length from a string,

This is working for maximum string but is not working for this coressponding array "What if we try a super-long word such as otorhinolaryngology"

You have

var largest = 0;
for (let i = 0; i <= largest; i++) {

You're iterating over the ar from indicies 0 to whichever index first sets largest to something larger than the current index. Use i < ar.length instead:

 function findLongestWordLength(str) { var res = str.split(" "); var ar = []; for (let i = 0; i < res.length; i++) { let leength = res[i].length; ar.push(leength); //ar is the array of the lengths of the word in the string. } var largest = 0; for (let i = 0; i < ar.length; i++) { if (ar[i] > largest) { var largest = ar[i]; } //this loop is detecting largest number from the array ar. } return largest; } console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"))

But spreading the mapped word lengths into Math.max might be easier:

 const findLongestWordLength = str => Math.max( ...str.split(' ').map(word => word.length) ); console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"))

Try splitting the input on whitespace, then sorting the array by length:

 var input = "What if we try a super-long word such as otorhinolaryngology"; var parts = input.split(/\\s+/); parts.sort(function(a, b) { return b.length - a.length; }); console.log(parts[0]);

 //Let us take an example let givenSen = "Shiva is a good guy"; //Here we are splitting with space //So we will get ["Shiva", "is", "a", "good", "guy"] //and sorting based on length //remeber ab (ascending order), ba (decending order) //0(zero) represents first element let largestWord = givenSen.split(" ").sort(function(a,b){return(b.length - a.length)})[0] //cosole console.log(largestWord.length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM