In JavaScript Show Longest Word in a String
Posted on November 28, 2017 in Algorithms, JavaScript, Regular Expressions by Matt Jennings

function longestWord(sen) { 
  // 'sen' is a string and 'match'
  // matches all the items in the 
  // 'sen' string (per the regex)
  // an array of matched parts of the string.
  // The '/a-z0-9+/gi' regular expression
  // matches a part of the string with letters or numbers
  // case insentively (the 'i') and 
  // globally (the 'g') which means that
  // not ONLY the first matching array element
  // will be returned and the '+' means
  // that a matching part of the string
  // will have one or more letters and/or numbers
  // matching.
  var arr = sen.match(/[a-z0-9]+/gi);

  // The function below returns an array of sorted
  // elements from the longest length element to the 
  // shortest length element. If two elements
  // are of equal length then the array element that
  // comes first is sorted before the element
  // that came second.
  var sorted = arr.sort(function(a, b) {
    return b.length - a.length;

  // The first element of the 'sorted' array is returned
  // because it is either the longest length array element
  // or tied for the longest length array element.
  return sorted[0];        
// Output is "coderbyte999"
console.log(longestWord("the $$$longest# word is coderbyte999")); 


Leave a Reply

To Top ↑