Javascript Interview Question String Get longest word

Introduction

Given a string. Find the length of longest word.

function findLongestWord(str) {
  //your code
}

console.log(findLongestWord('The quick brown fox jumped over the lazy moon'));


function longestWord(str) {
  var words = str.split(' ');  //creates an array of words
  var maxLength = 0;

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
    }
  }
  return maxLength;
}

console.log(longestWord('The yellow hippo')); // 6
console.log(longestWord('The first touchdown')); // 9
console.log(longestWord('The art of winning')); // 7
console.log(longestWord('Dumb and Dumber')); // 6


// Solution 2

function findLongestWord(str) {
  // Turns single string into an array of strings
  var arr = str.split(' ');
  // Set length of longest string to 0
  var longestString = '';
  // For loop to iterate through array of strings
  for (var i =0; i < arr.length; i++) {
    // compare longest string to next iteration in array. if longer, replace
    if(longestString.length < arr[i].length) {
      longestString = arr[i];
    }
  }
    // str is now replaced with the longest length
    str = longestString;
    return str.length;
  }

console.log(findLongestWord('The quick brown fox jumped over the lazy moon'));

Write a method that takes in a string. Return the longest word in the string.

You may assume that the string contains only letters and spaces.

You may use the String split() method.

function longest_word(sentence) {
  //your code//w w w  .  j  av a2s. com
}

// These are tests to check that your code is working. After writing
// your solution, they should all print true.

console.log( longest_word( 'short longest' ) === 'longest' )
console.log( longest_word( 'one' ) === 'one' )
console.log( longest_word( 'abc def abcde' ) === 'abcde' )



function longest_word(sentence) {
  array = sentence.split(" ")
  var longest = "";
  for (i=0; i<= array.length -1; i++){    
    if(array[i].length > longest.length){
      longest = array[i];
    }
  }
  return longest;
}

// These are tests to check that your code is working. After writing
// your solution, they should all print true.

console.log( longest_word( 'short longest' ) === 'longest' )
console.log( longest_word( 'one' ) === 'one' )
console.log( longest_word( 'abc def abcde' ) === 'abcde' )



PreviousNext

Related