Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Mapping string to Numerals in JavaScript
We are required to write a JavaScript function that takes in a string. It should print out each number for every corresponding letter in the string.
Letter to Number Mapping
Each letter corresponds to its position in the alphabet:
a = 1 b = 2 c = 3 d = 4 e = 5 ... y = 25 z = 26
Note: The function should remove any special characters and spaces, processing only alphabetic characters.
Example Input and Output
If the input is:
"hello man"
Then the output should be:
"8,5,12,12,15,13,1,14"
Implementation
const str = 'hello man';
const charPosition = str => {
str = str.split('');
const arr = [];
const alpha = /^[A-Za-z]+$/;
for(let i = 0; i
8,5,12,12,15,13,1,14
How It Works
The function works by:
- Converting the string into an array of characters using
split('') - Using a regex pattern
/^[A-Za-z]+$/to identify alphabetic characters - Converting each letter to lowercase and using
charCodeAt(0) - 96to get its position (since 'a' has ASCII value 97) - Collecting all positions in an array and converting to a comma-separated string
Alternative Approach
Here's a more concise version using modern JavaScript methods:
const mapStringToNumbers = (str) => {
return str.toLowerCase()
.split('')
.filter(char => char >= 'a' && char char.charCodeAt(0) - 96)
.join(',');
}
console.log(mapStringToNumbers('hello man'));
console.log(mapStringToNumbers('JavaScript123!'));
8,5,12,12,15,13,1,14 10,1,22,1,19,3,18,9,16,20
Conclusion
This function effectively maps each letter to its alphabetical position while ignoring non-alphabetic characters. The charCodeAt() method combined with ASCII arithmetic provides an efficient solution for character-to-number conversion.
Advertisements
