Longest Word

Description


Define a word as a sequence of consecutive English letters. Find the longest word from the given string.

Example

For text = "Ready, steady, go!", the output should be longestWord(text) = "steady".

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] string text

Guaranteed constraints: 4 ≤ text.length ≤ 50.

  • [output] string

The longest word from text. It’s guaranteed that there is a unique output.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
function longestWord(text) {
    var words = text.match(/\w+/g);
    
    var ml = Math.max(...words.map(el=>el.length))
    
    for(var i=0;i< words.length; i++){
        if(words[i].length == ml)
            return words[i]
    }
}