Find longest word in string - JavaScript

巧了我就是萌 提交于 2021-02-19 07:26:07

问题


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


回答1:


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;
}



回答2:


Simplified code with no arrays and no each statements.

function longer(champ, contender) {
  return (contender.length > champ.length) ? contender: champ;
}

function longestWord(str) {
    var words = str.split(' ');
    return words.reduce(longer);
}
console.log(longestWord('This is longest'));
console.log(longestWord('This is longest or may this is more longestest'));



回答3:


Check this one:

function longest(s){
    return typeof s != 'string' ? '' : s.split(' ').sort( (a,b) => b.length - a.length)[0]
}

The input is converted into string through concatenation with an empty string so that it works when a number is passed as well.



来源:https://stackoverflow.com/questions/44111701/find-longest-word-in-string-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!