
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Finding shortest word in a string in JavaScript
- Finding second smallest word in a string - JavaScript
- Finding the longest string in an array in JavaScript
- Forming the longest word in JavaScript
- Finding the length of longest vowel substring in a string using JavaScript
- Finding the longest consecutive appearance of a character in another string using JavaScript
- Finding the longest valid parentheses JavaScript
- Finding longest consecutive joins in JavaScript
- Finding the longest substring uncommon in array in JavaScript
- Finding the character with longest consecutive repetitions in a string and its length using JavaScript
- Finding the longest "uncommon" sequence in JavaScript
- Finding all valid word squares in JavaScript
- Finding longest line of 1s in a matrix in JavaScript
- Finding the length of second last word in a sentence in JavaScript
- Finding mistakes in a string - JavaScript
Advertisements