Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find longest word in string - JavaScript

I am currently on a task in python and i need help with this and i am to

Write a function called longest which will take a string of space separated words and will return the longest one.

For example:

longest("This is Andela") => "Andela"
longest("A") => "A"

This is the sample test

const assert = require("chai").assert;

describe("Module 10 - Algorithyms", () => {
describe("longest('This Is Andela')", () => {
    let result = longest("This Is Andela");
    it("Should return 'Andela'", () => {
        assert.equal(result, 'Andela');
    });
});

describe("longest('This')", () => {
    let result = longest("This");
    it("Should return 'This'", () => {
        assert.equal(result, 'This');
    });
});

describe("longest(23)", () => {
    let result = longest(23);
    it("Should return ''", () => {
        assert.equal(result, '');
    });
});
});

This is what i have tried

function longest(str) {
str = "This is Andela";
var words = str.split(' ');
var longest = '';

for (var i = 0; i < words.length; i++) {
  if (words[i].length > longest.length) {
    longest = words[i];
  }
}
return longest;
}

But my code seem to only pass the first test case.Please what do i need to change to pass the other two first case considering i am new to javascript

like image 577
diagold Avatar asked Feb 18 '26 23:02

diagold


1 Answers

You need to remove this line in your function:

str = "This is Andela";

You function should be (added check if str is string):

function longest(str) {
    if(typeof str !== 'string') return '';
    var words = str.split(' ');
    var longest = '';

    for (var i = 0; i < words.length; i++) {
      if (words[i].length > longest.length) {
        longest = words[i];
      }
    }
    return longest;
}
like image 199
Victor Leontyev Avatar answered Feb 21 '26 12:02

Victor Leontyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!