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
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"
Example
Following is the code −
const str = 'hello man';
const charPosition = str => {
str = str.split('');
const arr = [];
const alpha = /^[A-Za-z]+$/;
for(i=0; i < str.length; i++){
if(str[i].match(alpha)){
const num = str[i].charCodeAt(0) - 96;
arr.push(num);
}else{
continue;
};
};
return arr.toString();
}
console.log(charPosition(str));
Output
This will produce the following output in console −
"8,5,12,12,15,13,1,14"
Advertisements