
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Calculating the weight of a string in JavaScript
Weight of a character (alphabet):
The weight of an English alphabet is nothing just its 1-based index.
For example, the weight of 'c' is 3, 'k' is 11 and so on.
We are required to write a JavaScript function that takes in a lowercase string and calculates and returns the weight of that string.
Example
The code for this will be −
const str = 'this is a string'; const calculateWeight = (str = '') => { str = str.toLowerCase(); const legend = 'abcdefghijklmnopqrstuvwxyz'; let weight = 0; const { length: l } = str; for(let i = 0; i < l; i++){ const el = str[i]; const curr = legend.indexOf(el); weight += (curr + 1); }; return weight; }; console.log(calculateWeight(str));
Output
And the output in the console will be −
172
- Related Articles
- Calculating h index of a citation in JavaScript
- Calculating average of a sliding window in JavaScript
- Calculating the LCM of multiple numbers in JavaScript
- Calculating least common of a range JavaScript
- Calculating the sum of digits of factorial JavaScript
- Calculating the balance factor in a Javascript AVL Tree
- Calculating average of an array in JavaScript
- Calculating median of an array in JavaScript
- Calculating the area of a triangle using its three sides in JavaScript
- Calculating resistance of n devices - JavaScript
- Calculating median of an array JavaScript
- Calculating a number from its factorial in JavaScript
- Maximum weight transformation of a given string in C++
- Calculating excluded average - JavaScript
- Weight sum of a nested array in JavaScript

Advertisements