- 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 1-based index score of a lowercase alpha string in JavaScript
Problem
We are required to write a JavaScript function that takes in a lowercase alphabet string. The index of ‘a’ in alphabets is 1, of ‘b’ is 2 ‘c’ is 3 … of ‘z’ is 26.
Our function should sum all the index of the string characters and return the result.
Example
Following is the code −
const str = 'lowercasestring'; const findScore = (str = '') => { const alpha = 'abcdefghijklmnopqrstuvwxyz'; let score = 0; for(let i = 0; i < str.length; i++){ const el = str[i]; const index = alpha.indexOf(el); score += (index + 1); }; return score; }; console.log(findScore(str));
Output
Following is the console output −
188
Advertisements