- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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