
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Replace a Letter with Its Alphabet Position in JavaScript
We are required to write a function that takes in a string, trims it off any whitespaces, converts it to lowercase and returns an array of numbers describing corresponding characters positions in the english alphabets, any whitespace or special character within the string should be ignored.
For example −
Input → ‘Hello world!’ Output → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]
The code for this will be −
Example
const str = 'Hello world!'; const mapString = (str) => { const mappedArray = []; str .trim() .toLowerCase() .split("") .forEach(char => { const ascii = char.charCodeAt(); if(ascii >= 97 && ascii <= 122){ mappedArray.push(ascii - 96); }; }); return mappedArray; }; console.log(mapString(str));
Output
The output in the console will be −
[ 8, 5, 12, 12, 15, 23, 15, 18, 12, 4 ]
Advertisements