Skip to content Skip to sidebar Skip to footer

Longest Word In Sentence Code Not Working

Can anyone help me solve this. It does not seem to be working properly. It is supposed to find the longest word of any string of words entered into it. When I run it, it returns th

Solution 1:

The split method returns a new array. Try this:

var arr = sen.split(" ");
for(var i = 0; i < arr.length; i++) {
    var check1 = arr[i];
    if(check1.length>lrg.length) {
        lrg = check1;
    }
}

return lrg; 

Solution 2:

You can also make use of regular expression for checking if a string matches or not.

var sentence = "seperates sen into words";
var splittedParts = sentence.match(/\w{1,}/gi);//You can also make use of regular //expressionfor(var i = 0; i < splittedParts.length; i++) {
    var check1 = splittedParts[i];
    if(check1.length>=splittedParts.length) {
        splittedParts = check1;
    }
}
  alert(splittedParts);

Solution 3:

If you match words and sort by length, longest first,

the first word in the array will be the longest.

functionlongestWord(str){
    return str.match(/[a-zA-Z]+/g).sort(function(a, b){
        if(a.length=== b.length) return a<b? 1: a>b? -1: 0;
        return b.length-a.length;
    })[0];
}
var s1= 'It\'s more like it is today, than it ever was before.';


longestWord(s1)

/* returned value: (String): before */

You can return an array of the same length with filter-

functionlongestWords(str){
    return str.match(/[a-zA-Z]+/g).sort(function(a, b){
        if(a.length=== b.length) return a<b? 1: a>b? -1: 0;
        return b.length-a.length;
    }).filter(function(w, i, A){
        return w.length=== A[0].length;
    });
}

var s1= 'It  became more like it is today, than it ever did before.';
longestWords(s1)

/* returned value: (Array): before,became */

Post a Comment for "Longest Word In Sentence Code Not Working"