
- 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
Replace a letter with its alphabet position 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 ]
- Related Articles
- Swapping letter with succeeding alphabet in JavaScript
- Replace alphabets with nth forward alphabet in JavaScript
- Convert number to alphabet letter JavaScript
- Find letter's position in Alphabet using Bit operation in C++
- Replace array value from a specific position in JavaScript
- JavaScript function to accept a string and mirrors its alphabet
- How to shift each letter in the given string N places down in the alphabet in JavaScript?
- Program to make vowels in string uppercase and change letters to next letter in alphabet (i.e. z->a) in JavaScript
- Replace commas with JavaScript Regex?
- Validate input: replace all ‘a’ with ‘@’ and ‘i’ with ‘!’JavaScript
- How to Replace null with “-” JavaScript
- Finding word starting with specific letter in JavaScript
- Capitalize a word and replace spaces with underscore - JavaScript?
- Replace a child node with a new node in JavaScript?
- Change every letter to next letter - JavaScript

Advertisements