-4

i'm trying to print the longest word from a string and to ignore the number, so even though the number is the longest, it will print the longest word.

let userInput = "print the longest word 3372838236253 without number"; 

function longestWord(userInput) {
    let x = userInput.split(" ");
    let longest = 0;
    let word = null;
    x.forEach(function(x) {
        if (longest < x.length) {
            longest = x.length;
            word = x;
        }
    });
    return word;
}

console.log(longestWord(userInput));
Alexandr Tovmach
  • 3,071
  • 1
  • 14
  • 31
orela123
  • 11
  • 2
  • 2
    Along with the `longest < x.length` condition, check if `x` is a number. [Check if a string is a valid number](https://stackoverflow.com/q/175739) – adiga Dec 29 '20 at 09:31

1 Answers1

1

Check word to be a number with isNumeric

let userInput = "print the longest word 3372838236253 without number"; 

function isNumeric(num){
  return !isNaN(num) && !isNaN(parseFloat(num))
}

function longestWord(userInput) {
    let words = userInput.split(" ");
    let longest = 0;
    let word = null;
    words.forEach(function(w) {
        if (longest < w.length && !isNumeric(w)) {
            longest = w.length;
            word = w;
        }
    });
    return word;
}

console.log(longestWord(userInput));
Alexandr Tovmach
  • 3,071
  • 1
  • 14
  • 31