简体   繁体   中英

Splitting a string before finding longest word

I have read a few different posts on this so I am sorry to ask this again but none seemed to solve my issue.

I'm trying to draw out the length of the longest word in a string, that is coming from HTML.

All I can get is, "Uncaught TypeError: Cannot read property 'split' of undefined"

The HTML:

<p id="p">I'm looking for the longest length of a word in this sentence</p>
<button onclick="longestWordFunc()">Click</button>

The JS:

var myString = document.getElementById("p");


function longestWordFunc(myString) {
  var stringSplit = myString.split(" ");
  var longestWord = 0;

  for(var i = 0; i < stringSplit.length; i++){
    if(longestWord >= stringSplit[i].length){

      longestWord = stringSplit[i].length;   
    }
   }

  return longestWord;
 }

Use reduce to iterate over the array starting with an empty string and return the longest of the two on each iteration.

The reason you are getting the undefined error is because myString is a parameter of your function and you are passing nothing into it, hence undefined.

 var myString = document.getElementById("p").innerText; function longestWordFunc() { return myString.split(" ").reduce((longest, current) => current.length > longest.length ? current : longest, ''); } 
 <p id="p">I'm looking for the longest length of a word in this sentence</p> <button onclick="console.log(longestWordFunc())">Click</button> 

Try this:

 <p id="p">I'm looking for the longest length of a word in this sentence</p>
 <button onclick="longestWordFunc()">Click</button>

In your JS, try adding .innerHTML to the end of your myString function. Also it was checking for 0 to be greater than or equal to the current stringSplit element.

 function longestWordFunc() {
     var myString = document.getElementById("p").innerHTML;
     var stringSplit = myString.split(" ");
     var longestWord = 0;

    for(var i in stringSplit) {
        if(longestWord <= stringSplit[i].length){
        longestWord = stringSplit[i].length;   
    }
    return longestWord;
 }

I see one problem and one possible one.

  1. The inequality is reversed, should be longestWord < stringSplit[i].length

  2. Perhaps you are defining myString before the element is created? (Eg, in the head of the html). That might be why myString is undefined. One solution for this is to move the definition into the function call, so that myString is only defined when the button is clicked.

     function longestWordFunc() { var myString = document.getElementById("p") var stringSplit = myString.textContent.split(" "); var longestWord = 0; for(var i = 0; i < stringSplit.length; i++){ if(longestWord < stringSplit[i].length){ longestWord = stringSplit[i].length; } } return longestWord; } 

Try this:

 var text = "I'm looking for the longest length of a word in this sentence" findLongestWord = (str) => { let split = str.split(" "); let longest = ""; split.forEach((word) => { if (word.length > longest.length) { longest = word; } }); return longest; } let longest = findLongestWord(text); console.log(`Longest Word: ${longest} - ${longest.length}`); 

If you just want the length of the longest word instead of returning the word itself you can have the findLongestWord function return this:

return longest.length

Hope this helps.

Using reduce as Adrian explained is a great way to achieve your goal in JS.

But if your target was to learn some of the basics of coding, here are some hints on how to make your current code work.

 function longestWordFunc() { var myString = document.getElementById("p").innerText; // Just the inner text var stringSplit = myString.split(" "); var longestWord = 0; //Index of longest word var longestLength=0; //Length of longest word for(var i = 0; i < stringSplit.length; i++){ if(stringSplit[i].length>longestLength){ // The other way around longestLength = stringSplit[i].length; longestWord=i; } } console.log(stringSplit[longestWord]); return stringSplit[longestWord]; } 
 <p id="p">I'm looking for the longest length of a word in this sentence</p> <button onclick="longestWordFunc()">Click</button></br> 

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