- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 average word length of sentences - JavaScript
We are required to write a JavaScript function that takes in a string of strings joined by whitespaces. The function should calculate and return the average length of all the words present in the string rounded to two decimal places
Example
Following is the code −
const str = 'This sentence will be used to calculate average word length'; const averageWordLength = str => { if(!str.includes(' ')){ return str.length; }; const { length: strLen } = str; const { length: numWords } = str.split(' '); const average = (strLen - numWords + 1) / numWords; return average.toFixed(2); }; console.log(averageWordLength(str)); console.log(averageWordLength('test test'));
Output
Following is the output in the console −
5.00 4.00
- Related Articles
- Finding special kind of sentences (smooth) in JavaScript
- Finding the length of second last word in a sentence in JavaScript
- JavaScript Compare two sentences word by word and return if they are substring of each other
- Finding average age from array of Objects using JavaScript
- Finding all valid word squares in JavaScript
- Finding the length of a JavaScript object
- Finding second smallest word in a string - JavaScript
- Finding shortest word in a string in JavaScript
- Finding word starting with specific letter in JavaScript
- Finding average of n top marks of each student in JavaScript
- Finding length of repeating decimal part in JavaScript
- Finding maximum length of common subarray in JavaScript
- Finding sum of remaining numbers to reach target average using JavaScript
- Finding average in mixed data type array in JavaScript
- Finding the longest word in a string in JavaScript

Advertisements