Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Finding the longest word in a string in JavaScript
We are required to write a JavaScript function that takes in a string as the only argument. The function should then iterate through the string and find and return the longest word from the string.
For example −
If the input string is −
const str = 'Coding in JavaScript is really fun';
Then the output string should be −
const output = 'JavaScript';
Example
Following is the code −
const str = 'Coding in JavaScript is really fun';
const findLongest = (str = '') => {
const strArr = str.split(' ');
const word = strArr.reduce((acc, val) => {
let { length: len } = acc;
if(val.length > len){
acc = val;
};
return acc;
}, '');
return word;
};
console.log(findLongest(str));
Output
Following is the output on console −
JavaScript
Advertisements
