Find the Longest word in a String

Coderbytes Exercise 3- find the length of the longest word in a string, ignore punctuation

by Jason Land

JavaScript

/*//find the longest word in a string
function LongestWord(sen) {
    var aSentenceLength = sen.split(/[ ,!?;:.']/); //split str into array on any of these characters
    var vLWArrayPosition = 0;
    var vLongestWord = 0;
    for (i = 0; i < aSentenceLength.length; i++) {
        var vTestWord = aSentenceLength[i]; //var equals single array element
        if (vTestWord.length > vLongestWord) { //if length of testword is longer than longestword...
            vLongestWord = vTestWord.length; //push testword value into longestword
            vLWArrayPosition = i; //store the array position if a push was made
        }
    }

    if (vLongestWord == 1) {
        alert(alert(aSentenceLength[vLWArrayPosition] + " is " + vLongestWord + " character long."));
    } else {
        alert(aSentenceLength[vLWArrayPosition] + " is " + vLongestWord + " characters long.");
    }

} */

// LongestWord("The world is not enough!");



function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
            word = str[i];
        }
    }
    alert(word);
    return word;
}

longestWord("What is the lognest word here?");