Skip to content Skip to sidebar Skip to footer

Splitting Sentence Into Array Of Words

folks, I'm trying to find out what word is the longest in an entered sentence but the code is not outputting anything. Could smb please help me with that? &l

Solution 1:

Change your regexp code to:

var splitted = sentence.split(/\s+/);

EDIT: below is a slightly different take on the function:

functionlongestWord(str) {
    return str.split(/\s+/).sort(function(w1, w2) {return w2.length - w1.length;})[0];    
}

var phrase = "dmitriy nesterkin drd";
console.log(longestWord(phrase));

Solution 2:

var length = 0;
var longestWord = "";
sentence.split(" ").forEach(function(word){
  if(word.length > length) {
    length = word.length;
    longestWord = word;
  }
});
document.write("The longest word in the sentence is " + longestWord);

Solution 3:

Here's a simplified version, using split and reduce. First spotted word prevails.

var longestWord = sentence.split(' ').reduce(function(longestWord, word){
  return word.length > longestWord.length ? word : longestWord;
}, '');

Solution 4:

You could make a compare function for the sort() function easily. This way you can check if there is more than one word that matches the length of the longest word, by popping the resulting sorted array.

functioncompare_words(a, b) { return a.length - b.length; }

var words = ["Hello", "here", "are", "some", "words", "of", "variable", "length"];

console.log("Longest word is: " + words.sort(compare_words).pop());

Post a Comment for "Splitting Sentence Into Array Of Words"