Skip to content
Advertisement

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;
 }

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement