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
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.
Problem Example
Input ? 'Hello world!' Output ? [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]
How It Works
The algorithm processes each character by:
- Converting to lowercase to handle both cases uniformly
- Getting ASCII code using
charCodeAt() - Checking if it's a letter (ASCII 97-122 for a-z)
- Converting ASCII to alphabet position by subtracting 96
Implementation
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));
[ 8, 5, 12, 12, 15, 23, 15, 18, 12, 4 ]
Alternative Approach Using Regular Expressions
const mapStringRegex = (str) => {
return str
.toLowerCase()
.replace(/[^a-z]/g, '') // Remove non-letters
.split('')
.map(char => char.charCodeAt(0) - 96);
};
console.log(mapStringRegex('Hello world!'));
console.log(mapStringRegex('Programming123'));
[ 8, 5, 12, 12, 15, 23, 15, 18, 12, 4 ] [ 16, 18, 15, 7, 18, 1, 13, 13, 9, 14, 7 ]
Method Comparison
| Method | Approach | Performance | Readability |
|---|---|---|---|
| forEach + ASCII check | Manual character validation | Good | Verbose but clear |
| RegEx + map | Pattern matching | Good | Concise |
Key Points
- ASCII values: 'a' = 97, 'z' = 122
- Alphabet position = ASCII code - 96
- Non-alphabetic characters are filtered out
- Case-insensitive processing via
toLowerCase()
Conclusion
Both approaches effectively convert letters to their alphabet positions while filtering non-alphabetic characters. The forEach method offers explicit control, while the regex approach provides cleaner, more functional code.
Advertisements
