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
Trying to get number for each character in string - 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.
For example,
a = 1 b = 2 c = 3 d = 4 e = 5 . . . Y = 25 Z = 26
Therefore, if the input is "hello man",
Then the output should be a number for each character ?
"8,5,12,12,15,13,1,14"
How It Works
The solution uses the charCodeAt() method to get the ASCII value of each character, then subtracts 96 to convert lowercase letters to their position numbers (a=1, b=2, etc.).
Example
Following is the code ?
const str = 'hello man';
const charPosition = str => {
str = str.split('');
const arr = [];
const alpha = /^[A-Za-z]+$/;
for(let i = 0; i < str.length; i++){
if(str[i].match(alpha)){
const num = str[i].toLowerCase().charCodeAt(0) - 96;
arr.push(num);
}
}
return arr.toString();
}
console.log(charPosition(str));
Output
This will produce the following output in console ?
8,5,12,12,15,13,1,14
Alternative Approach Using Map
Here's a more modern approach using array methods:
const str = 'hello man';
const getCharNumbers = (text) => {
return text.split('')
.filter(char => /[a-zA-Z]/.test(char))
.map(char => char.toLowerCase().charCodeAt(0) - 96)
.join(',');
}
console.log(getCharNumbers(str));
8,5,12,12,15,13,1,14
Key Points
-
charCodeAt(0)returns the ASCII code of the character - Subtracting 96 converts lowercase letters to position numbers (a=97, 97-96=1)
- Using
toLowerCase()ensures both uppercase and lowercase letters work - The regex
/[a-zA-Z]/filters out non-alphabetic characters like spaces
Conclusion
This method effectively converts each letter in a string to its alphabetical position using ASCII values. The approach works for both uppercase and lowercase letters while ignoring non-alphabetic characters.
